[英]Mocking vue-router's push() method in Unit testing - Vue 3
我是 Vue 和 StackOverflow 的新手,但我會嘗試解釋我的問題。
當我嘗試為我的應用程序運行單元測試時,我得到一個 TypeError。
“TypeError:無法讀取未定義的屬性(讀取'push')”
https://i.stack.imgur.com/pqUkZ.png
程序完全按照它應該運行的方式運行,只有測試失敗。
測試嘗試在應用程序中運行 $router.push ,但不能,因為它不知道那是什么,如何在測試時成功模擬 push 方法?
我的 example.spec.js 測試代碼如下所示:
import { shallowMount } from '@vue/test-utils'
import LoginView from '@/views/LoginView.vue'
describe('LoginView.vue', () => {
it('loginSuccess-test', async () => {
const wrapper = shallowMount(LoginView, {
mocks: {
$router: {
push: () => {}
}
}
})
await wrapper.setData({username:'user', password:'pass'})
await wrapper.find('button').trigger('click')
const statusId = wrapper.find('#loginstatusLabel');
expect(wrapper.find('#loginstatusLabel').element.textContent).toBe('true')
})
})
我的 LoginView.vue 方法代碼如下所示:
methods: {
checkCredentials() {
if (this.username === 'user' && this.password === 'pass') {
this.loginSuccess = 'true';
this.$router.push({ name: 'home' });
}
else {
this.toast.error("Username or password is incorrect Try again");
this.message = 'Login failed!';
this.isActive = false;
}
}
</script>
當用戶成功登錄並在測試中模擬重定向時,我試圖讓 push 方法將用戶重定向到“家”。
任何幫助將不勝感激
嘗試這個:
mocks: { $router: { push: jest.fn(), } }
在 vue3 中,您需要將mocks
屬性包裝在global
屬性中
Vue2
const wrapper = shallowMount(LoginView, {
mocks: {
$router: {
push: () => {}
}
}
})
Vue3
const wrapper = shallowMount(LoginView, {
global: {
mocks: {
$router: {
push: () => {}
}
}
}
})
來源: https://test-utils.vuejs.org/guide/advanced/vue-router.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.