使用 jest 模拟特定 url 上的 axios 请求

bat*_*roz 5 javascript testing mocking typescript jestjs

我想知道是否可以根据 url 来模拟具有不同值的 axios 请求。我使用笑话和打字稿。现在我有这个工作示例:

import axios from 'axios';
import { mocked } from 'ts-jest';
jest.mock('axios');
    
const mAxios = mocked(axios, true);
mAxios.get.mockResolvedValue({
  data: [
    {
      id: 1,
      title: 'john doe',
    },
    {
      id: 2,
      title: 'keyboard cat',
    },
  ],
});
Run Code Online (Sandbox Code Playgroud)

它可以工作,但正如您所看到的,无论请求发送到哪里,它总是返回相同的值。我想知道如何才能实现我的目标。

小智 0

使用.mockImplementation()回调:

import axios from 'axios';
import { mocked } from 'ts-jest';
jest.mock('axios');

const mAxios = mocked(axios, true);
mAxios.get.mockImplementation((url) => {
    switch (url) {
        case '/users.json':
            return Promise.resolve({data: [{id: 1, title: 'john doe'}]})
        case '/items.json':
            return Promise.resolve({data: [{id: 1, item: 'whatever'}]})
        default:
            return Promise.reject(new Error('not found'))
    })
}
Run Code Online (Sandbox Code Playgroud)