我需要使用 React 测试库和 Jest 在测试中模拟不同的窗口大小。
目前我必须拥有这个beforeAll
在每个测试文件中:
import matchMediaPolyfill from 'mq-polyfill';
beforeAll(() => {
matchMediaPolyfill(window)
window.resizeTo = function resizeTo(width, height) {
Object.assign(this, {
innerWidth: width,
innerHeight: height,
outerWidth: width,
outerHeight: height,
}).dispatchEvent(new this.Event('resize'))
}
})
我这样使用:
it('does something at small screen sizes', async () => {
window.resizeTo(320, 800);
// actual test here
我可以拥有一个全球beforeAll
这将适用于我的项目中的每个测试文件?
文档提到globalsetup
:
https://jestjs.io/docs/en/configuration#globalsetup-string https://jestjs.io/docs/en/configuration#globalsetup-string
但是它会出错,因为它无法识别beforeAll
功能。在我看来,该选项是用于设置环境但不向测试文件添加某些内容?