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

URL redirection testing with Vue.js and Jest

提问人:samb 提问时间:2/20/2018 更新时间:2/21/2018 访问量:11421

问:

我正在尝试编写一个测试来检查当用户单击“登录”按钮时,URL 是否被重定向到 。前端是用 Vue.js 编写的,测试是用 Jest 完成的。/auth/

以下是 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"

单元 测试 vue.js jestjs

评论


答:

12赞 samb 2/21/2018 #1

在一些帮助下,我可以使测试运行良好 https://forum.vuejs.org/t/url-redirection-testing-with-vue-js-and-jest/28009/2

这是最终测试(现在用 lib 编写):@vue/test-utils

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