【问题标题】:How do I mock a custom property of the window object in Jest?如何在 Jest 中模拟窗口对象的自定义属性?
【发布时间】:2021-03-11 12:08:57
【问题描述】:

我正在构建一个 ReactJS 17 应用程序并尝试测试以下调用是否与 Jest 一起发生。属性“dataObj”是我添加到全局窗口对象中的。

window.dataObj.send(event.name, ldo);

我正在我的测试中尝试这个......

  const dataObj = {
    send: jest.fn()
  };
    
  Object.defineProperty(window, 'dataObj', dataObj);
  console.log(window.dataObj);

但是当我查询“window.dataObj”(使用该 console.log 语句)时,它总是返回未定义。如何模拟窗口对象的属性?

【问题讨论】:

  • 你不需要defineProperty,除非该属性之前已经定义了一个。

标签: reactjs unit-testing jestjs mocking window


【解决方案1】:

您应该将dataObj 分配给描述符的value

例如

index.js:

export function main(event) {
  window.dataObj.send(event.name, 'ldo');
}

index.test.js:

import { main } from './';

describe('66574843', () => {
  it('should pass', () => {
    const dataObj = {
      send: jest.fn(),
    };

    Object.defineProperty(window, 'dataObj', {
      value: dataObj,
    });

    main({ name: 'teresa' });
    expect(dataObj.send).toBeCalledWith('teresa', 'ldo');
  });
});

测试结果:

 PASS  examples/66574843/index.test.js
  66574843
    ✓ should pass (4 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.755 s

【讨论】:

    猜你喜欢
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    相关资源
    最近更新 更多