【发布时间】: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