【问题标题】:How to mock multiple axios call with jest?如何用玩笑模拟多个 axios 调用?
【发布时间】:2021-11-04 19:56:33
【问题描述】:

在我的 Typescript 处理程序中,我有多个 axios 调用,如下所示

export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
const options = {
   headers: {
      Accept: 'application/json',
     'Content-Type': 'application/json;charset=UTF-8',
     authorization: 'Token',
   },
 }; 
    const respData = await axios
    .all([
      axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5', options),
      axios.get('https://jsonplaceholder.typicode.com/posts?_limit=5', options)
    ])
    .then(axios.spread((todos, posts) => {todos, posts}))
    .catch(err => console.error(err));

  return {
     statusCode: 200,
     body: JSON.stringify(respData),
  };

};

如何用 jest 模拟这些多个 API 调用?

【问题讨论】:

    标签: typescript unit-testing aws-lambda axios jestjs


    【解决方案1】:

    您可以使用jest.spyOn(object, methodName)mockFn.mockImplementation(fn) 根据url 参数模拟具有不同解析值的axios.get() 方法。

    此外,从文档 Concurrency (Deprecated) 中,我们知道 axios.all()axios.spread() 方法已被弃用。使用Promise.all 替换它们。

    main.ts:

    import axios from 'axios';
    
    interface APIGatewayProxyEvent {}
    interface APIGatewayProxyResult {}
    
    export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
      const options = {
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json;charset=UTF-8',
          authorization: 'Token',
        },
      };
      const respData = await axios
        .all([
          axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5', options),
          axios.get('https://jsonplaceholder.typicode.com/posts?_limit=5', options),
        ])
        .then(axios.spread((todos, posts) => ({ todos, posts })))
        .catch((err) => console.error(err));
    
      return { statusCode: 200, body: JSON.stringify(respData) };
    };
    

    main.test.ts:

    import { handler } from './main';
    import axios from 'axios';
    
    describe('69096350', () => {
      test('should pass', async () => {
        const axiosGetSpy = jest.spyOn(axios, 'get').mockImplementation(async (url) => {
          if (url === 'https://jsonplaceholder.typicode.com/todos?_limit=5') {
            return [1, 2, 3, 4, 5];
          } else if (url === 'https://jsonplaceholder.typicode.com/posts?_limit=5') {
            return ['a', 'b', 'c', 'd', 'e'];
          }
        });
        const actual = await handler({});
        expect(actual).toEqual({
          statusCode: 200,
          body: JSON.stringify({ todos: [1, 2, 3, 4, 5], posts: ['a', 'b', 'c', 'd', 'e'] }),
        });
        expect(axiosGetSpy).toBeCalledWith('https://jsonplaceholder.typicode.com/todos?_limit=5', {
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json;charset=UTF-8',
            authorization: 'Token',
          },
        });
        expect(axiosGetSpy).toBeCalledWith('https://jsonplaceholder.typicode.com/posts?_limit=5', {
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json;charset=UTF-8',
            authorization: 'Token',
          },
        });
        axiosGetSpy.mockRestore();
      });
    });
    

    测试结果:

     PASS  examples/69096350/main.test.ts (7.535 s)
      69096350
        ✓ should pass (4 ms)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |   88.89 |      100 |      75 |   85.71 |                   
     main.ts  |   88.89 |      100 |      75 |   85.71 | 20                
    ----------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        8.035 s, estimated 9 s
    Ran all test suites related to changed files.
    

    【讨论】:

      猜你喜欢
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2021-11-27
      • 2018-05-05
      • 2021-01-06
      • 2020-02-08
      相关资源
      最近更新 更多