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

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

问题描述

我有一个函数,它在节点和浏览器上运行,我想用 jest 测试它:

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;
}

如何将全局窗口对象设置为未定义,以测试节点分支,并返回 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

推荐答案

您可以尝试使用 @jest-environment 文档块,从 v20.0.0 开始可用,为不同的测试更改环境.默认情况下,它使用 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天全站免登陆