【问题标题】:How to Mock or SpyOn an exported function in React如何在 React 中模拟或监视导出的函数
【发布时间】:2020-09-26 03:38:25
【问题描述】:

我有一个默认导出的组件

// Component.js
export default () => <>getData()</>;
export const getData = async () => await fetch('/');

 

// Component.test.js
import Component from 'Component'

describe('test getData', () => {
    const getDataMock = jest.spyOn(Component, 'getData');
    expect(getDataMock).toBeCalledOnce();
})

我收到错误:无法监视 getData 属性,因为它不是函数;取而代之的是未定义

【问题讨论】:

  • 只是好奇 - 为什么不将 getData 移动到自己的文件中?
  • 因为它只和Component有关,而且很小。我不认为每个函数都应该是它自己的文件。
  • 什么是QueuesTable?您甚至在哪里尝试 spy on getData 会导致错误?
  • 复制时出错,已更新

标签: javascript jestjs enzyme


【解决方案1】:

您导入了默认函数而不是 getData。

// Component.test.js
import mydefault, * as notdefaults from 'Component';

test('test getData', () => {
    const getDataMocked = jest.spyOn(notdefaults, 'getData');
    getDataMocked.mockResolvedValue('hello!');
    expect(mydefault()).toBeDefined(); // call the default component to trigger getData()
    expect(getDataMocked).toBeCalledTimes(1);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-09
    • 2018-05-08
    • 1970-01-01
    • 2018-08-28
    • 2015-12-29
    • 2021-12-24
    • 2022-08-17
    • 2016-09-17
    相关资源
    最近更新 更多