我正试图编写一个测试来判断当用户点击"登录"按钮时,URL是否被重定向到/auth/.前端是用Vue编写的.js和测试是用Jest完成的.

以下是Vue组件如何重定向(从UserLogged.vue开始).它在浏览器中工作.

export default {
  name: 'UserLogged',
  props: ['userName'],
  methods: {
    login: function (event) {
      window.location.href = '/auth/'
    }
  }
}

下面是测试它的try :

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/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/').

Vue.js相关问答推荐

无法从CDN使用Vue和PrimeVue呈现DataTable

为什么 Pinia/Vuex 比使用服务类的classic 方法更受欢迎?

如何在 v-for 指令切换状态下安全地制作包含附加到对象的复选框的列表(W/O 切换列表中的其他复选框)?

如果单元格不可见,则以编程方式打开行的编辑模式. Ag 网格,Vue.js

aspnet core如何在deploy上构建webpack

v-for 内部的组件

正确使用 Vue $refs

带有外部配置文件的 Vue js

VueJS 将 HTML 打印到页面

如何创建 vuetify 工具栏链接下拉菜单?

Nuxt 打开链接到模态

为什么我在 vue.js 中得到避免使用 JavaScript 一元运算符作为属性名称?

按键删除对象不会更新vue组件

Vue CLI 3 sass-resources-loader - Options.loaders 未定义

找不到模块 'babel-core' 但已安装 @babel/core

无法访问函数内的数据属性

使用 Vue 的点击编辑文本字段

从子组件 Vue 更新父模型

如何使用vue js判断组件本身的数据何时发生变化?

如何将单选按钮绑定到 vuex store ?