首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用jest模拟多个axios调用

使用jest模拟多个axios调用
EN

Stack Overflow用户
提问于 2019-09-01 23:43:26
回答 2查看 9.2K关注 0票数 15

我刚刚发现了一种使用jest模拟axios的有用方法,然而,如果我使用不同的url多次调用axios,我如何根据url指定url和返回值呢?有没有办法不用第三方库就能做到呢?

谢谢

代码语言:javascript
运行
复制
    // 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));
});
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-02 00:24:50

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

代码语言:javascript
运行
复制
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}]}))
})
票数 27
EN

Stack Overflow用户

发布于 2021-07-09 01:55:04

这对我很管用。下面显示了你将在哪里以及如何渲染应用程序。

代码语言:javascript
运行
复制
  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();
  });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57747392

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档