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
Add a ment  | 

2 Answers 2

Reset to default 4

In 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