Jest.js 强制窗口未定义 [英] Jest.js force window to be undefined

查看:28
本文介绍了Jest.js 强制窗口未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jest + 酶设置进行测试.如果定义了窗口,我有有条件地呈现某些东西的函数.

在我的测试套件中,当未定义窗口时,我试图达到第二种情况,但我不能强制它.

<前>it('当窗口未定义时产生一些东西', () => {窗口 = 未定义;期望(myFunction()).toEqual(thisWhatIWantOnUndefinedWinow);});

但即使我强制窗口未定义,它也不会达到预期的情况,窗口始终是窗口(jsdom?)

这与我的笑话设置有关还是我应该以另一种方式处理?

解决方案

我能够使用以下模式测试未定义 window 的场景.它允许您在同一个文件中使用和不使用 window 运行测试.不需要在文件顶部添加@jest-environment node.

describe('当窗口未定义时', () => {const { 窗口 } = 全局;beforeAll(() => {//@ts-忽略删除 global.window;});afterAll(() => {global.window = 窗口;});it('运行没有错误', () => {...});});

I'm working with jest + enzyme setup for tests. I have function that conditionally renders something if window is defined.

In my test suite I'm trying to reach second case, when window is not defined, but I can't force it.


    it('makes something when window is not defined', () => {
       window = undefined;
       expect(myFunction()).toEqual(thisWhatIWantOnUndefinedWinow);
    });

But even if I force window to be undefined, it doesn't reach expected case, window is always window (jsdom?)

Is it something with my jest setup or I should handle this another way?

解决方案

I am able to test the scenario where window is undefined using the below pattern. It allows you to run tests with and without window in the same file. Adding @jest-environment node at the top of the file is not required.

describe('when window is undefined', () => {
    const { window } = global;
    beforeAll(() => {
      // @ts-ignore
      delete global.window;
    });
    afterAll(() => {
      global.window = window;
    });
    
    it('runs without error', () => {
      ...
    });
});

    

这篇关于Jest.js 强制窗口未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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