【问题标题】:$router.push not triggering in unit testing$router.push 未在单元测试中触发
【发布时间】:2021-07-06 20:07:58
【问题描述】:

我在尝试对我的 Vue 应用程序进行单元测试时遇到以下问题。 即使监视和模拟 $router.push,我仍然无法在单元测试中调用它:

这是我的单元测试 (Home.spec.js)

const localVue = createLocalVue();

localVue.use(Vuex);
localVue.use(VueRouter);

describe('Home.vue', () => {
  let actions;
  let getters;
  let store;
  let router;

  beforeEach(() => {
    actions = {
        [FETCH_USER_REPOSITORIES]: jest.fn()
    };

    getters = {
       getTopThreeRepositories: jest.fn(repositoryMock.getRepositories)
    };

    store = new Vuex.Store({ getters, actions });
    router = new VueRouter();
  });

  it('should redirect when 404 status code received', async () => {
    jest.spyOn(store, 'dispatch').mockRejectedValue({ statusCode: 404 });
    jest.spyOn(router, 'push').mockResolvedValue({});

    const wrapper = await shallowMount(Home, {
        store,
        localVue,
        router
    });
    
    expect(router.push).toHaveBeenCalledWith('/not-found');
});

});

现在,这是我的 Home.vue

import { mapGetters } from 'vuex';
  import { FETCH_USER_REPOSITORIES } from "../store/actions";

  import RepositoryList from "@/components/RepositoryList";
  import Card from "@/components/Card";

  export default {
    name: 'view-home',
    components: {
      Card,
      RepositoryList
    },

    async beforeMount() {
      try {
        await this.$store.dispatch(FETCH_USER_REPOSITORIES, 'some-repo');
      } catch(err) {
        console.log(this.$router);
        await this.$router.push('/not-found');
      }
    },

    computed: {
      ...mapGetters(["getTopThreeRepositories"])
    }
  }

控制台日志正确显示了 $router 和 spy。 如果我在单元测试中强制调用,它可以工作,但是期望总是失败,让我返回 $router.push 没有被调用。

谁能帮帮我,好吗? 谢谢!

【问题讨论】:

    标签: vue.js jestjs vue-router


    【解决方案1】:

    您应该将$store$route 指定为mocks in your mounting options,如下所示。也不需要awaitshallowMount,因为shallowMount 不会返回Promise,所以await 会立即返回。

    describe('Home.vue', () => {
      it('should redirect when 404 status code received', () => {
        const $store = {
          dispatch: jest.fn()
        }
        const $router = {
          push: jest.fn()
        }
    
        const wrapper = shallowMount(Home, {
            localVue,
            mocks: {
              $store,
              $router,
            }
        });
        
        expect($router.push).toHaveBeenCalledWith('/not-found');
      })
    })
    

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      相关资源
      最近更新 更多