开玩笑地嘲笑global.window [英] mocking global.window in jest

查看:217
本文介绍了开玩笑地嘲笑global.window的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个既可以在节点又可以在浏览器中运行的函数,我想通过玩笑来对其进行测试:

I have a function, that runs on both node and in the browser, which I want to test with jest:

const myFn = () => {
  if(typeof window !== 'object'){
     return 1;
  }
  return 2;
}

如何将全局窗口对象设置为undefined,以测试节点分支,并返回1.

How am I able to set the global window object to undefined, to test the node branch, and that 1 is returned.

例如

  test('myTest', ()=> {
      global.window = undefined;
      expect(myFn()).toEqual(1); // result: 2
  });

我在这里尝试了建议,但没有成功: 在Jest中模拟全局变量

Ive tried the suggestions here with no success: Mocking globals in Jest

推荐答案

您可以尝试使用从v20.0.0开始可用的@jest-environment文档块,以更改不同测试的环境.默认情况下,它使用jsdom,但是您可以将其更改为使用node.这是他们文档的摘录:

You can try using the @jest-environment docblock, available since v20.0.0, to change the environment for different tests. By default it uses jsdom, but you can change it to use node. Here is an excerpt from their documentation:

/**
 * @jest-environment jsdom
 */

test('use jsdom in this test file', () => {
  const element = document.createElement('div');
  expect(element).not.toBeNull();
});

参考: https://facebook.github.io/jest/docs/en/configuration.html#testenvironment-string

这篇关于开玩笑地嘲笑global.window的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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