axios呼叫没有被嘲笑

时间:2018-05-02 05:27:32

标签: reactjs unit-testing axios sinon

My 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

问题是当我用开头的Axbed axios运行测试时,我总是得到以下结果的结果状态

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

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

1 个答案:

答案 0 :(得分:0)

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