ctimmerm / axios-mock-adapter

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

History of put requests is empty #196

Open mei33 opened 5 years ago

mei33 commented 5 years ago

I have simple Vue component that fetches API key when it is created and key can be renewed by clicking on button:

<template>
    <div>
        <div>{{data.api_key}}</div>
        <button ref="refresh-trigger" @click="refreshKey()">refresh</button>
    </div>
</template>
<script>
    export default {
        created() {
            axios.get(this.url).then((response) => {
                this.data = response.data
            })
        }
        methods: {
            refreshKey() {
                axios.put(this.url).then((response) => {
                    this.data = response.data
                })
            },
        }
    }
</script>

And I want to test it with this code:

import {shallowMount} from '@vue/test-utils';
import axios from 'axios';
import apiPage from '../apiPage';
import MockAdapter from 'axios-mock-adapter';

describe('API page', () => {
    it('should renew API key it on refresh', async (done) => {
        const flushPromises = () => new Promise(resolve => setTimeout(resolve))
        const initialData = {
            api_key: 'initial_API_key',
        };
        const newData = {
            api_key: 'new_API_key',
        };
        const mockAxios = new MockAdapter(axios);

        mockAxios.onGet('/someurl.json').replyOnce(200, initialData)
        mockAxios.onPut('/someurl.json').replyOnce(200, newData);

        const wrapper = shallowMount(api);
        expect(wrapper.vm.$data.data.api_key).toBeFalsy();

        await flushPromises()

        wrapper.vm.$nextTick(() => {
            expect(wrapper.vm.$data.data.api_key).toEqual(initialData.api_key);
            done()
        });

        wrapper.find({ref: 'refresh-trigger'}).trigger('click');

        wrapper.vm.$nextTick(() => {
            console.log(mockAxios.history)

            expect(wrapper.vm.$data.data.api_key).toEqual(newData.api_key);

            expect(mockAxios.history.get.length).toBe(1);
            expect(mockAxios.history.get[1].data).toBe(JSON.stringify(initialData));

            expect(mockAxios.history.put.length).toBe(1);
            done();
        });
    })
});

But it turns out only get request is mocked because i receive:

        [Vue warn]: Error in nextTick: "Error: expect(received).toEqual(expected)

Difference:

    - Expected
    + Received

    - new_API_key
    + initial_API_key"

found in

---> <Anonymous>
<Root>

console.error node_modules/vue/dist/vue.runtime.common.dev.js:1883
{ Error: expect(received).toEqual(expected)

Even worse, console.log(mockAxios.history) returns empty put array:

{ get:
   [ { transformRequest: [Object],
       transformResponse: [Object],
       timeout: 0,
       xsrfCookieName: 'XSRF-TOKEN',
       xsrfHeaderName: 'X-XSRF-TOKEN',
       maxContentLength: -1,
       validateStatus: [Function: validateStatus],
       headers: [Object],
       method: 'get',
       url: '/admin/options/api.json',
       data: undefined } ],
  post: [],
  head: [],
  delete: [],
  patch: [],
  put: [],
  options: [],
  list: [] }

I tried to define mockAxios in describe block, and console.log it after iteration - and it turns out that put request was here. But not when I needed it. :)

What am i doing wrong? Maybe there are some ways to check if created callback was called and all async functions inside it are done? Maybe i'm using axios-mock wrong?

zanedev commented 5 years ago

try using setTimeout instead of $nextTick, not sure why it matters but it worked for me.

mei33 commented 5 years ago

hey, thanks for advice. sounds strange, but hope it'll help. i'll try it

On Wed, May 22, 2019 at 11:49 PM ZaneDev notifications@github.com wrote:

try using setTimeout instead of $nextTick, not sure why it matters but it worked for me.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/ctimmerm/axios-mock-adapter/issues/196?email_source=notifications&email_token=AEK2BXB3RINN26PRZR2EYSDPWV2TNA5CNFSM4HCQ2AGKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGODV7VGNA#issuecomment-494883636, or mute the thread https://github.com/notifications/unsubscribe-auth/AEK2BXBT3ZF6D4HA7NRSOP3PWV2TNANCNFSM4HCQ2AGA .

-- Андреев Максим Александрович +7-923-331-3772