admin管理员组文章数量:1431904
I've been struggling to figure out how to properly test this code for days :(
const request = require('superagent');
const getDog = () => {
return request.get('/api/breeds/image/random');
};
it('resolves', () => {
// Expect mocked response
});
it('rejects', () => {
// Expect mocked response
});
I've been struggling to figure out how to properly test this code for days :(
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
});
Share
Improve this question
edited Jun 5, 2018 at 7:49
Joshua
3,2063 gold badges26 silver badges41 bronze badges
asked Jun 5, 2018 at 4:23
Alex MilesAlex Miles
3011 gold badge3 silver badges7 bronze badges
2
- Have you tried the method explained in superagent-mock, github./M6Web/superagent-mock – Adi Commented Jun 5, 2018 at 4:30
- I'd like to not use any other libraries other that jest if possible – Alex Miles Commented Jun 5, 2018 at 12:16
2 Answers
Reset to default 4In most cases, your code gets some value from API parses it and makes some stuff with it.
As a result, you don't want to make real API call and mock it instead.
There are a couple of ways to do it. One of the possible is to mock the only method on the superagent
library.
// 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'
});
});
I used expect.assertions(1)
, there is a reason:
This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.
There are links that can help you: mockFn.mockResolvedValue(value) , .rejects
One solution is to use a library such as nock or fetch-mock to mock out the HTTP response to your request.
本文标签: javascriptHow do I mock async fetches with jestStack Overflow
版权声明:本文标题:javascript - How do I mock async fetches with jest? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745583340a2664749.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论