reactjs - 使用 jest 模拟窗口等全局对象的字段
问题描述
我正在尝试为检测方向变化的小型实用程序类编写代码。不幸的是,我发现访问这些字段的唯一方法window.orientation
是window.screen.orientation
我可以看到它window.orientation
已被弃用。我发现的替代方法是 Safari 不支持的实验检测 api。所以我决定暂时坚持使用已弃用的 api,直到找到更好的东西。
尝试使用相同的方法时,我遇到了类似的问题window.orientation
。
本质上,我们试图改变的属性是只读属性。
在这种情况下正确的方法是什么?
请注意我在 lib.dom.d.ts 中看到的 window.orientation 的弃用警告
解决方案
您可以使用Object.defineProperty()来执行此操作。
例如
index.ts
:
export function main() {
const orientation = window.screen.orientation;
return orientation.type;
}
index.test.ts
:
import { main } from './';
describe('63570675', () => {
it('should pass', () => {
Object.defineProperty(window.screen, 'orientation', {
value: { type: 'landscape-primary' },
});
const actual = main();
expect(actual).toEqual('landscape-primary');
});
});
带有覆盖率报告的单元测试结果:
PASS src/stackoverflow/63570675/index.test.ts
63570675
✓ should pass (5ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.292s, estimated 14s
源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/63570675
推荐阅读
- javascript - 每当我尝试将 nodejs 与 sql sever 连接时,都会出现“无法连接到 localhost”的错误
- excel - 我的代码没有遍历每一行,而是在我的范围内打印第一行
- swift - 将项目附加到收藏夹
- reactjs - 使用 Azure API 管理运行 React 时如何配置 REST URL?
- gitlab - Runner 无法克隆 gitlab 存储库
- python - 显示 ForeignKey 对象的问题
- javascript - Why will my translation animation not work?
- c# - 在 EnumerateFiles() LINQ C# 中处理(跳过)UnauthorizedAccessException
- python - Remove string in list that is substring of another string if both are in the list
- powershell - 并行执行函数在powershell中引发错误