【问题标题】:URL redirection testing with Vue.js and Jest使用 Vue.js 和 Jest 进行 URL 重定向测试
【发布时间】:2018-07-31 00:55:27
【问题描述】:

我正在尝试编写一个测试来检查当用户单击“登录”按钮时,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"

【问题讨论】:

    标签: unit-testing testing vue.js jestjs


    【解决方案1】:

    https://forum.vuejs.org/t/url-redirection-testing-with-vue-js-and-jest/28009/2987654321@的帮助下,我可以很好地运行测试

    这是最后的测试(现在用@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/')

    【讨论】:

      猜你喜欢
      • 2023-02-07
      • 2020-07-04
      • 2019-02-20
      • 2019-11-04
      • 2018-07-28
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多