ctimmerm / axios-mock-adapter

Axios adapter that allows to easily mock requests
MIT License
3.47k stars 245 forks source link

Trying change the response of an onGet later in the test doesn't work #328

Closed sinner closed 2 years ago

sinner commented 2 years ago

Hi team, your project is very useful. Thank you very much.

I have the following test code:

describe("Test PreferencesView.vue component", () => {
    const mock = new MockAdapter(axios);
    let store;
    const dataList = [1, 2, 3];

    beforeEach(() => {
        store = GlobalStore;
        mock.reset();
        mock.onGet(/data/).reply(200, dataList);
    });

    it("should handle success response", async () => {
        const wrapper = shallowMount(MyComponent, {
            store,
            localVue
        });

        await flushPromises();

        expect(wrapper.vm.dataList instanceof Array).toBeTruthy();
        expect(wrapper.vm.dataList.length).toBe(dataList.length);
    });

    it("should handle errors properly", async () => {
        mock.onGet(/data/).replyOnce(500, { message: "Server Error" });

        const wrapper = shallowMount(MyComponent, {
            store,
            localVue
        });
        const spyHandleError = jest.spyOn(wrapper.vm, "showGenericErrorNotification");
        wrapper.vm.$nextTick();

        await flushPromises();

        expect(spyHandleError).toHaveBeenCalled();
    });

The idea of the test is setting up a default 200 HTTP response for all the request over /data/ regex URL expression in the beforeEach method, but I would like to change that behavior in some test cases.

The weird thing here is that the first test pass successfully, but, the second test when I'd like to test my component against an API error it turns out that the API doesn't return the expected 500 error, it always returns the 200 HTTP OK response that was configured in the beforeEach method.

I need to achieve this because there are some other test cases that depend on that 200 HTTP OK response.

Thank you very much in advance.

JeffreyStevens commented 2 years ago

I am having this problem as well in my unit tests. I want to test both success and error responses in the same set of tests.

ctimmerm commented 2 years ago

duplicate of #257