使用Interval在vueJS生命周期钩子中进行Async Jest测试

时间:2018-05-09 12:29:50

标签: unit-testing vue.js jest vuex

我想了解如何在“beforeCreate”钩子中测试我的“auth / refresh”动作,如下所示:

// main.vue

async beforeCreate() {
    let authTokenRefreshIntervalId;

    await this.$store.dispatch('auth/initialize');

    authTokenRefreshIntervalId = setInterval(() => {
      this.$store.dispatch('auth/refresh').catch(() => {
        this.$store.dispatch('auth/logout');
        clearInterval(authTokenRefreshIntervalId);
      });
    }, 30 * 1000);
}

// main.spec.js

import Vue from 'vue';
import Vuex from 'vuex';
import { shallow, createLocalVue, mount } from '@vue/test-utils';
import Main from '@/main';

const localVue = createLocalVue();

jest.useFakeTimers();

describe('store-auth', () => {
  let store;
  let actions;
  let getters;

  beforeEach(() => {
    actions = {
      initialize: jest.fn(),
      refresh: jest.fn(),
      logout: jest.fn(),
    };

    getters = {
      isAuthenticated: jest.fn(),
    };

    store = new Vuex.Store({
      modules: {
        auth: {
          namespaced: true,
          actions,
          getters,
        },
      },
    });
  });

  it('dispatch initialize on beforeCreate hook', () => {
    const wrapper = shallow(Main, { store, localVue });
    expect(actions.initialize).toHaveBeenCalled();
  });

  it('dispatch refresh on beforeCreate hook every 30s', () => {
    const wrapper = shallow(Main, { store, localVue });
    jest.runTimersToTime(30 * 1000);
    expect(actions.refresh).toHaveBeenCalled();
  });
});

Jest说没有调用模拟函数。 我尝试了expect(setInterval).toHaveBeenCalled()并通过了测试。 哪里我错了PLZ?

1 个答案:

答案 0 :(得分:0)

尝试在测试中使用async / await。

it('dispatch refresh on beforeCreate hook every 30s', async () => {
    const wrapper = shallow(Main, { store, localVue });
    jest.runTimersToTime(30 * 1000);
    await expect(actions.refresh).toHaveBeenCalled();
 });