几天来我一直在努力想办法正确地测试这段代码:(
const request = require('superagent');
const getDog = () => {
return request.get('https://dog.ceo/api/breeds/image/random');
};
it('resolves', () => {
// Expect mocked response
});
it('rejects', () => {
// Expect mocked response
});
最佳答案
在大多数情况下,您的代码会从 API 中获取一些值,然后对其进行解析并使用它来制作一些东西。
因此,您不想进行真正的 API 调用而是模拟它。
有几种方法可以做到这一点。一种可能是模拟 superagent
库中的唯一方法。
// tell jest not to mock superagent because we'll mock the only method
jest.unmock('superagent');
const request = require('superagent');
const getDog = () => {
return request.get('https://dog.ceo/api/breeds/image/random');
};
it('resolves', () => {
// mock the get request to resolve object
request.get = jest.fn().mockResolvedValue({
message: 'Your message'
});
// Expect mocked response
expect.assertions(1);
return expect(getDog()).resolves.toEqual({
message: 'Your message'
});
});
it('rejects', () => {
// mock the get request to reject object
request.get = jest.fn().mockRejectedValue({
message: 'Your error'
});
// Expect mocked response
expect.assertions(1);
return expect(getDog()).rejects.toEqual({
message: 'Your error'
});
});
我使用了expect.assertions(1)
,有一个reason :
This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.
有些链接可以帮助您: mockFn.mockResolvedValue(value) , .rejects
关于javascript - 我如何用 Jest 来模拟异步提取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50692010/