如何修复vue.js测试工具中的jest window.alert或null错误? [英] How to fix jest window.alert or null error in vuejs test utils?

查看:120
本文介绍了如何修复vue.js测试工具中的jest window.alert或null错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试我的Vue组件,但遇到了一些该死的疯狂错误,我做了人们喜欢使用jsdom的事情,但没有解决它,并不断显示这些错误:

I want to test my vue components, but i ran into some damn crazy errors, which i did what people like using jsdom, didn't fix it, and keeps showing these errors:

  console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
      Error: Not implemented: window.alert

 [Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'addEventListener' of null"

我有一个Header组件,它的安装位置是:

I have a Header component, which its mounted is :

    methods: {
.
.
.
      addEventHandler(...args: any) {
        addEventHandler(...args);
      }
    },
mounted() {
  this.addEventHandler('.dej_search', 'enter', '.dej_suggestion .active-item', this.enterSection);
  //@ts-ignore
  this.addEventHandler('', 'ctrl+f||f3', 'GeneralSearch', id => document.getElementById(id).focus());
}

,事件处理程序代码如下:

and the eventhandler code is below:

//addEventHandler.js:
import Vue from "vue"
import {keyboardCodes} from "@/utils/keyboardCodes";


const {enter, f, f3} = keyboardCodes;
export const addEventHandler = (domSelector = '',
                                event = '',
                                data = '',
                                eventHandler = (item) => {
                                }
) => {
  let dom = domSelector !== '' ? document.querySelector(domSelector) : window;
  switch (event) {
    case "enter":
      dom.addEventListener("keypress", (e) => {
        let key = e.which || e.keyCode || 0;
        if (key === enter) {
          eventHandler(data);
          e.preventDefault();
        }
      });
      break;
    case "ctrl+f||f3":
      dom.addEventListener("keydown", (e) => {
        let key = e.which || e.keyCode || 0;
        if (key === f3 || (e.ctrlKey && key === f)) {
          eventHandler(data);
          e.preventDefault();
        }
      });
      break;
    default:
      console.log("event ....");
      break;
  }
};

如您所见,我也使用了jsdom,但是我没有解决该问题,我真的很困惑如何解决这些问题并进行一些单元测试而不会在jest框架中感到痛苦.

As you can see i also used the jsdom, but i didnt fix the problem, and i really am confused to how should i fix these problems and do some unit test without pain in jest framework.

//header.test.js

import {mount, shallowMount} from "@vue/test-utils";
import Header from "../../../src/views/pages/Panel/Header";
import {JSDOM}  from "jsdom";

const dom = new JSDOM()
document = dom.window.document;
window = dom.window;
window.alert = jest.fn();

describe("mount",()=>{
  const wrapper = shallowMount(Header);
  console.log(wrapper.vm);
  console.log(wrapper.element);
});

我们应该如何消除这些错误?

How should we get rid of these errors?

.....

更新

我可以修复window.alert错误.由于不支持的笑话,或者无法在cli中测试ui,因此无法测试某些功能,例如alert,或者很难测试

I could fix the window.alert error. because of jest which doesnot support or in anotherway it is not possible to test ui in the cli, so some functionalties like alert cannot be tested or it is hard to test which is mentioned by https://jestjs.io/docs/en/tutorial-jquery . so to fix the window.alert problem we can add an equal implementation or empty one just to prevent test from failing:

window.alert = () => {};  // provide an empty implementation for window.alert
// or 
window.alert = (text) => {console.log(text)};  // provide an non-empty implementation for window.alert

但是我真的不知道如何模拟我在addEventHandler.js中使用的document.getElementById来防止'addEventListener'为null的错误. 有什么好的解决办法吗?

but i really doesn't any idea how to mock the document.getElementById which i used in the addEventHandler.js to prevent such error for 'addEventListener' of null". is there any good solution to this?

推荐答案

window.alert和其他一些特定于浏览器的副作用需要手动添加.最好使用Jest完成此操作,以便可以跟踪并清理间谍:

window.alert and several other browser-specific side effects needs to be stubbed manually. This should preferably be done with Jest, so a spy could be tracked and cleaned up:

jest.spyOn(window, 'alert').mockReturnValue();

然后可以断言对window.alert的调用.

Calls to window.alert can be asserted then.

如果JSDOM自动将其存根,那么弊大于利.这很少有问题,因为alert对UI/UX不友好,并且在生产代码中并不常见.

If JSDOM stubbed it automatically, this would do more harm than good. This is rarely a problem because alert is unfriendly to UI/UX and uncommon in production code.

TypeError:无法读取null的属性"addEventListener"

TypeError: Cannot read property 'addEventListener' of null

表示该元素不存在.这可能是由于该组件安装得较浅且未完全渲染所致,这通常是单元测试的首选策略.

means that the element doesn't exist. This probably is caused by that the component was shallowly mounted and wasn't rendered entirely, which is generally a preferable strategy for unit testing.

可以模拟addEventListener方法或具有addEventListener的模块,以防止访问DOM:

Either addEventListener method or a module with addEventListener can be mocked to prevent the access to DOM:

jest.mock('.../addEventListener', () => ({ addEventListener: jest.fn() }));

也可以断言对addEventListener的调用.

这篇关于如何修复vue.js测试工具中的jest window.alert或null错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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