Pep*_*ito 4 javascript jestjs jest-dom
我使用 jest-dom 和 jsdom 在 Jest 中测试窗口的高度。
使用此代码:
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 !
})
})
Run Code Online (Sandbox Code Playgroud)
结果是一个错误,说:
预期:150
收到:768
使用innerWidth,接收值为1024
太好了,这意味着可以使用 Jest 和 jest-dom 测试窗口的大小。
但是 768 和 1024 是从哪里来的呢?它是默认值吗?将永远是?它是否可配置以及如何配置?
768 和 1024 是默认值,Jest 正在为您的测试配置 jsdom。
您可以在测试中覆盖 window.innerHeight。但是 TypeScript 说不,因为 window 是不可写的成员。
对我来说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);
});
});
Run Code Online (Sandbox Code Playgroud)
使用 Object.defineProperty 和 TS 的示例在这里找到:How to test a media query css apply to an element on screen resize using jest andase in reactjs
| 归档时间: |
|
| 查看次数: |
4205 次 |
| 最近记录: |