Jest.js强制窗口未定义



我正在使用jest+酶设置进行测试。我有一个函数,若定义了窗口,那个么它会有条件地渲染一些东西。

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

it('在未定义窗口时生成某些内容',((=>{window=未定义;expect(myFunction(((.toEqual(thisWhatIWantOnUndefinedWinow(;})

但即使我强制窗口未定义,它也没有达到预期的情况,窗口总是窗口(jsdom?(

这是我的玩笑设置,还是我应该用另一种方式处理?

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

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

it('runs without error', () => {
...
});
});

以下是我在选定的jest测试中强制window未定义的操作。

使用窗口进行测试=未定义

您可以通过在一些测试文件的顶部添加@jest-environment node来强制窗口未定义。

测试窗口未定义。spec.js

/**
* @jest-environment node
*/
// ^ Must be at top of file
test('use jsdom in this test file', () => {
console.log(window)
// will print 'undefined' as it's in the node environment  
});

使用窗口进行测试

如果您需要window对象,只需删除顶部的语句即可。

这归功于这里的答案

告诉你它对我有效

const windowDependentFunction = () => {
if (typeof window === 'undefined') {
return 'window does not exist'
}
return 'window exist'
}
it('should verify if window exist', () => {
Object.defineProperty(global, 'window', {
value: undefined,
})
expect(windowDependentFunction()).toEqual('window does not exist')
})

最新更新