[英]Vue.js testing: props validation,how to test Vue console.error log with JEST
[英]URL redirection testing with Vue.js and Jest
我正在嘗試編寫一個測試,以檢查當用戶單擊“登錄”按鈕時,URL是否重定向到/auth/
。 前端是用Vue.js編寫的,而測試是用Jest完成的。
這是Vue組件(從UserLogged.vue
)重定向的方式。 它可以在瀏覽器中使用。
export default {
name: 'UserLogged',
props: ['userName'],
methods: {
login: function (event) {
window.location.href = '/auth/'
}
}
}
這是測試它的嘗試:
import Vue from 'vue'
import UserLogged from '@/components/UserLogged'
describe('UserLogged.vue', () => {
it('should redirect anonymous users to /auth/ when clicking on login button', () => {
const Constructor = Vue.extend(UserLogged)
const vm = new Constructor().$mount()
const button = vm.$el.querySelector('button')
// Simulate click event
// Note: the component won't be listening for any events, so we need to manually run the watcher.
const clickEvent = new window.Event('click')
button.dispatchEvent(clickEvent)
vm._watcher.run()
expect(window.location.href).toEqual('http://testserver/auth/')
})
})
測試輸出將給出"http://testserver/"
而不是預期的"http://testserver/auth"
。
我可以在一些幫助下使測試順利運行https://forum.vuejs.org/t/url-redirection-testing-with-vue-js-and-jest/28009/2
這是最終測試(現在使用@vue/test-utils
lib編寫):
import {mount} from '@vue/test-utils'
import UserLogged from '@/components/UserLogged'
describe('UserLogged.vue', () => {
it('should redirect anonymous users to /auth/ when clicking on login button', () => {
const wrapper = mount(UserLogged)
const button = wrapper.find('button')
window.location.assign = jest.fn() // Create a spy
button.trigger('click')
expect(window.location.assign).toHaveBeenCalledWith('/auth/');
})
})
順便說一句,我不得不在components/UserLogged.vue
window.location.href = '/auth/'
更改為window.location.assign('/auth/')
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.