首页 > 解决方案 > 使用 jest 模拟窗口等全局对象的字段

问题描述

我正在尝试为检测方向变化的小型实用程序类编写代码。不幸的是,我发现访问这些字段的唯一方法window.orientationwindow.screen.orientation

我可以看到它window.orientation已被弃用。我发现的替代方法是 Safari 不支持的实验检测 api。所以我决定暂时坚持使用已弃用的 api,直到找到更好的东西。

现在我面临的另一个挑战是在模拟对这些只读字段的访问时 在此处输入图像描述

尝试使用相同的方法时,我遇到了类似的问题window.orientation

本质上,我们试图改变的属性是只读属性。

在这种情况下正确的方法是什么?

请注意我在 lib.dom.d.ts 中看到的 window.orientation 的弃用警告

标签: reactjsdommockingjestjsreact-testing-library

解决方案


您可以使用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


推荐阅读