使用Vue.js和Jest进行URL重定向测试 [英] URL redirection testing with Vue.js and Jest

查看:38
本文介绍了使用Vue.js和Jest进行URL重定向测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a test to checks that when the user clicks on "login" button, the URL is redirected to /auth/. Frontend is written with Vue.js and testing is done with Jest.

这是Vue组件(从 UserLogged.vue )重定向的方式.它可以在浏览器中使用.

Here is how the Vue component redirects (from UserLogged.vue). It works in the browser.

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" .

Test output gives "http://testserver/" instead of expected "http://testserver/auth".

推荐答案

在一些帮助下,我可以使测试很好地运行

I could make the test run nicely with some help https://forum.vuejs.org/t/url-redirection-testing-with-vue-js-and-jest/28009/2

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

Here is the final test (now written with @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 .

BTW, I had to change window.location.href = '/auth/' to window.location.assign('/auth/') in components/UserLogged.vue.

这篇关于使用Vue.js和Jest进行URL重定向测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆