我用小丑和jsdom测试窗口的高度。
使用此代码:
import '@testing-library/jest-dom'
describe('test window height'), () => {
test('test the height'), () => {
expect(window.innerHeight).toBe(150) // 150 is an arbitrary value for testing the test !
})
}) 其结果是一个错误,即:
预期: 150
收到: 768
对于innerWidth,接收值为1024。
这很好,这意味着窗口的大小与Jest和jest是可测试的。
但是768和1024从哪里来呢?它是默认值吗?它是可配置的吗?如何配置?
发布于 2020-03-23 15:54:31
768和1024是默认的,Jest正在为您的测试配置jsdom。
您可以在测试中覆盖window.innerHeight。但是TypeScript说不行,因为窗口是一个不可写的成员。
对我来说,Object.defineProperty与TypeScript的工作方式如出一辙。
因此,对于JEST,这个测试应该通过绿色测试:
describe('test window height', () => {
it('test the height',
() => {
Object.defineProperty(window, 'innerHeight', {
writable: true,
configurable: true,
value: 150,
});
window.dispatchEvent(new Event('resize'));
expect(window.innerHeight).toBe(150);
});
});在TS中使用Object.defineProperty的示例:How to test that a media query css applies to an element upon screen resize using jest and enzyme in reactjs
https://stackoverflow.com/questions/60396600
复制相似问题