gpt4 book ai didi

javascript - 如何针对特定的 axios 调用模拟 jest.spyOn

转载 作者:行者123 更新时间:2023-12-02 22:04:50 24 4
gpt4 key购买 nike

如何模拟特定的 axios 调用?想象一下 2 个 GET 调用:

await axios.get('api/numbers');
await axios.get('api/letters');

那么测试中是这样的:

const mockGet = jest.spyOn(axios, 'get');
mockGet.mockReturnValueOnce(Promise.resolve({ data: 1 }));
mockGet.mockReturnValueOnce(Promise.resolve({ data: 'a' }));

如何根据传递给 axios 的 url 创建 mockReturnValueOnce 的条件(例如 'api/numbers' -> return Promise.resolve( { 数据:1 }))

最佳答案

到目前为止,jestjs 还没有方法可以做到这一点。这是建议:Parameterised mock return values

解决办法如下:

  1. 使用sinon.js

sinon.js 支持根据参数模拟返回值,有一个方法名为 stub.withArgs(arg1[, arg2, ...]);

  • 使用jest-when - 用于 Jest 的when(fn).calledWith(args).thenReturn(value) lib

  • 如果您坚持使用 jestjs,因为 mockReturnValueOnce 按顺序返回值(第一次调用、第二次调用等)。您可以使用以下方式:

  • index.js:

    import axios from 'axios';

    export async function main() {
    const numbersRes = await axios.get('api/numbers');
    const lettersRes = await axios.get('api/letters');
    return { numbersRes, lettersRes };
    }

    index.test.js:

    import { main } from '.';
    import axios from 'axios';

    describe('59751925', () => {
    it('should pass', async () => {
    const mockGet = jest.spyOn(axios, 'get');
    mockGet.mockImplementation((url) => {
    switch (url) {
    case 'api/numbers':
    return Promise.resolve({ data: 1 });
    case 'api/letters':
    return Promise.resolve({ data: 'a' });
    }
    });
    const actual = await main();
    expect(actual.numbersRes).toEqual({ data: 1 });
    expect(actual.lettersRes).toEqual({ data: 'a' });
    });
    });

    单元测试结果:

     PASS  src/stackoverflow/59751925/index.test.js (11.168s)
    59751925
    ✓ should pass (9ms)

    Test Suites: 1 passed, 1 total
    Tests: 1 passed, 1 total
    Snapshots: 0 total
    Time: 13.098s

    关于javascript - 如何针对特定的 axios 调用模拟 jest.spyOn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59751925/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com