【问题标题】:Using jest to mock multiple axios calls使用 jest 模拟多个 axios 调用
【发布时间】:2020-01-04 22:15:07
【问题描述】:

我刚刚发现了这种使用 jest 模拟 axios 的有用方法,但是,如果我多次调用具有不同 url 的 axios,我如何指定 url 和根据 url 返回的值? 有什么方法可以在不使用 3rd 方库的情况下做到这一点?

谢谢

    // users.test.js
import axios from 'axios';
import Users from './users';

jest.mock('axios');

test('should fetch users', () => {
  const users = [{name: 'Bob'}];
  const resp = {data: users};
  axios.get.mockResolvedValue(resp);

  // or you could use the following depending on your use case:
  // axios.get.mockImplementation(() => Promise.resolve(resp))

  return Users.all().then(data => expect(data).toEqual(users));
});

【问题讨论】:

    标签: javascript unit-testing jestjs axios


    【解决方案1】:

    您可以在.mockImplementation() 回调中处理多个条件:

    jest.mock('axios')
    
    axios.get.mockImplementation((url) => {
      switch (url) {
        case '/users.json':
          return Promise.resolve({data: [{name: 'Bob', items: []}]})
        case '/items.json':
          return Promise.resolve({data: [{id: 1}, {id: 2}]})
        default:
          return Promise.reject(new Error('not found'))
      }
    })
    
    test('should fetch users', () => {
      return axios.get('/users.json').then(users => expect(users).toEqual({data: [{name: 'Bob', items: []}]}))
    })
    
    test('should fetch items', () => {
      return axios.get('/items.json').then(items => expect(items).toEqual({data: [{id: 1}, {id: 2}]}))
    })
    

    【讨论】:

    【解决方案2】:

    它对我有用。下面显示了您将在何处以及如何呈现应用程序。

      it("should work.", async () => {
        let component;
        await act(() => {
          return axios.get("https://api.address.here.com/").then(async (res) => {
            component = renderer.create(<App />);
          });
        });
        expect(component.toJSON()).toMatchSnapshot();
      });
    

    【讨论】:

      猜你喜欢
      • 2020-11-06
      • 2023-04-02
      • 2022-07-21
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 2018-12-18
      相关资源
      最近更新 更多