使用Vue.js和Jest进行URL重定向测试

时间:2018-02-20 15:46:07

标签: unit-testing testing vue.js jestjs

我正在尝试编写测试来检查当用户点击“登录”按钮时,该网址会重定向到/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"

1 个答案:

答案 0 :(得分:3)

我可以通过一些帮助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/');
  })
})

顺便说一句,我必须在window.location.href = '/auth/'中将window.location.assign('/auth/')更改为components/UserLogged.vue