vue шут маршрутизатор неправильный маршрут - PullRequest
1 голос
/ 17 марта 2020

Я сейчас пишу юнит-тесты для наших vue компонентов. У меня проблема в том, что если тест привел к маршрутизатору $router.push, у объекта роутера в jest все равно будет тот же маршрут, что и wrapper.vm.$route.name, который был получен в предыдущем тесте.

Я перепробовал все, что мог сбрасывать его после каждого теста, но безуспешно. Может быть, у вас есть идея. Вот мой код:

import {
// @ts-ignore
createLocalVue, RouterLinkStub, mount, enableAutoDestroy,
} from '@vue/test-utils';
import VueRouter from 'vue-router';
import Vuex from 'vuex';
import Component from '../../../components/account/Password.vue';
import routes from '../../../router/index';
import CustomerModuleStore, { CustomerModule } from '../../../store/modules/CustomerModule';
import Constants from '../../../constants';

jest.mock('../../../store/modules/CustomerModule');

const localVue = createLocalVue();
localVue.use(Vuex);
localVue.use(VueRouter);

let customerModule: CustomerModuleStore;

enableAutoDestroy(afterEach);

describe('Password.vue', () => {
    const router = new VueRouter({
        routes: routes.options.routes,
    });

    function mountStore() {
        const store = new Vuex.Store({});
        customerModule = new CustomerModule({ store, name: 'customer' });
        customerModule.changePassword = jest.fn().mockImplementation(() => Promise.resolve());

        return mount(Component, {
            provide: {
                customerModule,
            },
            localVue,
            store,
            router,
            stubs: { 'router-link': RouterLinkStub },
            attachToDocument: true,
        });
    }

    describe('Test component initialisation', () => {
        let wrapper;

        beforeEach(() => {
            wrapper = mountStore();
        });

        it('is a Vue instance', () => {
            expect(wrapper.isVueInstance()).toBeTruthy();
        });

        it('should render with the router', () => {
            expect(wrapper.element).toBeDefined();
        });
    });

    it('redirects to correct route', async () => {
        const submitButton = wrapper.find({ ref: 'submitButton' });
        expect(submitButton.attributes().disabled).toBe('disabled');

        // method content excluded for readability (fills inputs and triggers change event)
        fillFormWithValidData(wrapper);

        await wrapper.vm.$nextTick();

        submitButton.trigger('click');

        await wrapper.vm.$nextTick();

        // this.$router.push({ name: 'Home' }); got executed in component
        expect(wrapper.vm.$route.name).toBe('Home');
    });

    describe('Test error response functionality', () => {
        let wrapper;

        beforeEach(() => {
            wrapper = mountStore();
        });

        test('button is enabled if all data is valid by default', async () => {
            const submitButton = wrapper.find({ ref: 'submitButton' });
            expect(submitButton.attributes().disabled).toBe('disabled');

            // method content excluded for readability (fills inputs and triggers change event)
            fillFormWithValidData(wrapper);

            await wrapper.vm.$nextTick();

            submitButton.trigger('click');

            await wrapper.vm.$nextTick();

            // this.$router.push({ name: 'Home' }); did not get executed in component
            // but test fails since $route.name is still 'Home'
            expect(wrapper.vm.$route.name).not.toBe('Home');
        });
    });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...