开玩笑地嘲笑global.window [英] mocking global.window in 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;
}
如何将全局窗口对象设置为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屋!