$router.push 未在单元测试中触发
Posted
技术标签:
【中文标题】$router.push 未在单元测试中触发【英文标题】:$router.push not triggering in unit testing 【发布时间】: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 没有被调用。
谁能帮帮我,好吗? 谢谢!
【问题讨论】:
【参考方案1】:您应该将$store
和$route
指定为mocks
in your mounting options,如下所示。也不需要await
shallowMount
,因为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');
)
)
【讨论】:
以上是关于$router.push 未在单元测试中触发的主要内容,如果未能解决你的问题,请参考以下文章
Spring HATEOAS Resource assembler 未在单元测试中实例化
茉莉花匹配器功能未在 angularjs/karma 单元测试中加载