【问题标题】:axios call not getting mockedaxios 调用没有被嘲笑
【发布时间】:2018-05-02 05:27:31
【问题描述】:

我的 React 组件使用 Axios 调用 API。在我的单元测试中,我试图通过使用来自 Sinon 的 Sandbox 存根来模拟 Axios,如下所示:

sandbox1 = sandbox.create();
            const resolved = new Promise((r) => r([{ id: 1, name: 'PetA' }, { id: 2, name:'PetB' }]));
            sandbox1.stub(axios, 'get').returns(resolved);

我想测试下面这段代码

this.setState(
            ({ testing }) => ({
                testing: {
                    ...testing,
                    [testKey]: {
                        isExecuting: true,
                        response: null
                    }
                }
            }),
            () => {
                axios(req)
                    .then(r => {
                        this.setState(state => {
                            const cancelled =
                                state.testing &&
                                state.testing[testKey] &&
                                state.testing[testKey]['cancelled'];
                            return !cancelled
                                ? {
                                    test: {
                                        ...state.test,
                                        [testKey]: {
                                            isExecuting: false,
                                            cancelled: false,
                                            response: r
                                        }
                                    }
                                  }
                                : undefined;
                        });
                    })


this is followed by catch block 
and closed paranthesis of setState

问题是当我使用 stubbed axios 运行测试时,如开头所示,我总是得到以下结果状态

{ testing: { 'get_/pets': { isExecuting: true, response: null } } }

这意味着 axios 没有解决承诺,尽管在存根时给出了指令。请帮忙。

【问题讨论】:

    标签: reactjs unit-testing axios sinon


    【解决方案1】:

    在您的测试中,您应该使用存根函数,因此您应该调用axios.get(req) 而不是调用axios.get(req),因为axios 因为函数没有被存根

    【讨论】:

    • 感谢您的输入..实际上 axios(req) 在需要测试的代码中,而不是在测试中...在测试中,我有这行:sandbox1.stub(axios , 'get').returns(已解决);
    猜你喜欢
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 2020-04-23
    • 2018-12-24
    • 2021-11-30
    相关资源
    最近更新 更多