测试是否在挂钩中调用了窗口函数

问题描述

我有一个需要在react钩子中模拟的函数:window.analytics.identify并测试它是否被调用

function useNiceHook(data) {
  useEffect(() => {
    ...
      window.analytics.identify(
        ...
  },[data])
}

export { useNiceHook }

我正试图像这样

windowSpy.mockImplementation(() => ({
        analytics: {
          identify: jest.fn(),},}))

然后测试:

renderHook(() => useNiceHook(data))
expect(window.analytics.identify).toBeCalled()

但是我目前测试失败:

Error: expect(jest.fn()).toBeCalled()

Expected number of calls: >= 1
Received number of calls:    0

解决方法

单元测试解决方案:

index.js

import { useEffect } from 'react';

function useNiceHook(data) {
  useEffect(() => {
    window.analytics.identify();
  },[data]);
}

export { useNiceHook };

index.test.js

import { useNiceHook } from './';
import { renderHook } from '@testing-library/react-hooks';

describe('63401335',() => {
  it('should pass',() => {
    const mAnalytics = {
      identify: jest.fn(),};
    Object.defineProperty(window,'analytics',{
      value: mAnalytics,});
    const data = {};
    renderHook(() => useNiceHook(data));
    expect(mAnalytics.identify).toBeCalled();
  });
});

具有覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/63401335/index.test.js
  63401335
    ✓ should pass (24ms)

----------|----------|----------|----------|----------|-------------------|
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:        5.13s,estimated 13s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/63401335

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...