首页 > 解决方案 > 400 上 axios 模型的 nock 不返回定义的值

问题描述

我正在使用 nock 来模拟我的 ajax 调用与 axios。这是我的代码:

    describe("unSuccessful rest call",()=>{

    it('should dispatch types: SET_DROP_DOWN_CHECK_STATUS in order ', () => {
        nock(getRootUrl(ServiceUrls.prototype.getContactUsUrl())).get(getExtention(ServiceUrls.prototype.getContactUsUrl())).replyWithError(400, "test");


        const expectedActions = [
            {
                "type": SET_DROP_DOWN_CHECK_STATUS,
                "payload": "test"
            }
        ];


        return store.dispatch(setContactUsList({push:()=>{}})).then(() => {
            expect(store.getActions()[0]).to.eql(expectedActions[0]);

        })
    })


})

当我运行上述测试时,它会访问服务器并返回实际的错误消息,而不是我要求的测试。有趣的是,当我将上述代码用于 200 时,它成功返回了我定义的内容。谁能帮助我的方法有什么问题?

标签: reactjsaxioschainock

解决方案


不确定 nock 有什么问题,因为我尝试使用它并遇到了类似的问题。我使用axios-mock-adapter并发现了一个更简单的工具。

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';

const mock = new MockAdapter(axios);

afterEach(() => {
    mock.reset();
});

it('should fail when trying to search for documents', async () => {

        mock.onGet(SEARCH_ENDPOINT + formattedFields).reply(400, {
            details: [
                {
                    code: 400,
                    message: 'No claim number or DCN provided'
                }
            ]
        });

        const given = { fields: activeFields };
        const expected = [
            { type: types.FETCH_DOCS_STARTED },
            { type: types.FETCH_DOCS_FAILED, message: 'No claim number or DCN provided' }
        ];

        await store.dispatch(actions.fetchDocs(given));

        const actualDispatchedActions = store.getActions();
        expect(actualDispatchedActions).toEqual(expected);
    });

推荐阅读