我在用酶的支架测试React钩子。看起来没有调用React钩子useEffect。
这是我的功能组件:
export function HelloFetch() {
  type HelloData = { Message: any }
  const initialHelloData : HelloData = { Message: "" };
  const url = `https://localhost:1000/api/hello`;
  const [helloData, setHelloData] = useState(initialHelloData);
  useEffect(() => {
    fetch(
      url,
      {
        method: "GET"
      }
    )
    .then(res  => res.json() )
    .then(response => {
      setHelloData(response)
      console.log(response)
    })
     . catch(error => console.error(error));
  });
  return (
    <div>
        <div>
          <p>Fetch: </p>{helloData.Message}
        </div>
    </div>
  );
}api应该返回"hello,world",它在postman中也是这样做的。它在浏览器中看起来也很好。
{"Message":"Hello, world"}这是我的测试代码:
describe('Hello', () => {
    const helloFetchComponent = mount(<HelloFetch />);
    it(' using fetch api should contain "Hello, world"', () => {
      expect(helloFetchComponent.html()).toContain("Hello, world");
    });
}我得到了这个错误:
Expected substring: "Hello, world"
Received string:    "<div><div><p>Fetch: </p></div></div>" 我尝试使用react- testing -library的render方法来测试它。
test('renders hello world app', () => {
  const { getByText } = render(
    <HelloFetch />
  );
  expect(getByText('Hello')).toBeInTheDocument();
});这是我得到的错误:
renders hello world app
    Unable to find an element with the text: Hello. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
<body>
  <div>
    <div>
      <div>
        <p>
          Fetch:
        </p>
      </div>
    </div>
  </div>
</body>我不确定我错过了什么。
编辑:重新发布我的评论到@Florian这里,以便更好地格式化。
我从fetch切换到axios。我有以下几点:
describe('Hello', () => { 
    it(' using axios should contain "mock Hello, world"', () => { 
        const mock = new MockAdapter(axios); 
        const mockData : HelloData = { Message: "mock Hello, world"}; 
        mock.onGet(helloUrl).reply(200, mockData); 
        let component = mount(<HelloAxios />); 
        expect(component.html()).toContain("mock Hello, world"); 
    }) 
}) 即使api工作正常,组件也不包含来自api的数据。
以下方法确实起作用:
axios.get(helloUrl).then(function (response) { 
    expect(response.data.html()).toContain("mock Hello, world"); 
});我不知道如何让mount和MockAdapter一起工作。
发布于 2020-05-16 23:48:04
Fetch在Node中不可用,Jest在Node中执行测试。
您不应该尝试在您的单元测试中进行真正的HTTP调用,您应该使用Jest awesome工具模拟它们:https://jestjs.io/docs/en/mock-functions.html
或者你也可以使用https://github.com/jefflau/jest-fetch-mock。
模拟负责API调用的函数:
import * as ModuleExportingAsyncFunction from 'ModuleExportingAsyncFunction'
const mockedThings = [{...}, {...}];
jest.spyOn(ModuleExportingAsyncFunction, 'getThingsReturnPromise').mockReturnValue(Promise.resolve(mockedThings));
// no more real HTTP calls !https://stackoverflow.com/questions/61808791
复制相似问题