sam*_*amb 8 testing unit-testing vue.js jestjs
我正在尝试编写一个测试来检查当用户单击“登录”按钮时,URL 是否重定向到/auth/. 前端是用 Vue.js 编写的,测试是用 Jest 完成的。
下面是 Vue 组件如何重定向(从UserLogged.vue)。它在浏览器中工作。
export default {
name: 'UserLogged',
props: ['userName'],
methods: {
login: function (event) {
window.location.href = '/auth/'
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是测试它的尝试:
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/')
})
})
Run Code Online (Sandbox Code Playgroud)
测试输出给出"http://testserver/"而不是预期的"http://testserver/auth"。
sam*_*amb 10
我可以在一些帮助下使测试运行良好https://forum.vuejs.org/t/url-redirection-testing-with-vue-js-and-jest/28009/2
这是最终测试(现在用@vue/test-utilslib编写):
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/');
})
})
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我不得不更改window.location.href = '/auth/'为window.location.assign('/auth/')in components/UserLogged.vue。