如何在 Jest 中模拟 window 对象的自定义 属性?

How do I mock a custom property of the window object in Jest?

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

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

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

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

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

您应该将 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