javascript - Jest - 模拟一个函数被导入到你正在测试的组件文件中

标签 javascript unit-testing testing jestjs enzyme

我有一个要使用 jest 测试的类组件。该组件正在使用从 utils 文件导入的函数。如何从我的主测试文件中模拟导入的函数?

最佳答案

您可以使用 jest.spyOn(object, methodName)方法,这里是一个完整的演示:

idnex.tsx:

import React, { Component } from 'react';
import { someHelper } from './utils';

class SomeComponent extends Component {
  render() {
    return <div>some component, {someHelper()}</div>;
  }
}

export default SomeComponent;

utils.ts:

export const someHelper = () => 'return value';

index.spec.tsx:

import React from 'react';
import SomeComponent from './index';
import * as utils from './utils';
import { shallow } from 'enzyme';

describe('SomeComponent', () => {
  beforeEach(() => {
    jest.restoreAllMocks();
  });
  test('should mock utils', () => {
    const someHelperSpy = jest.spyOn(utils, 'someHelper').mockReturnValue('mocked return value');
    const wrapper = shallow(<SomeComponent></SomeComponent>);
    expect(jest.isMockFunction(utils.someHelper)).toBeTruthy();
    expect(wrapper.text()).toBe('some component, mocked return value');
    expect(someHelperSpy).toBeCalled();
  });
});

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

 PASS  src/stackoverflow/58521281/index.spec.tsx
  SomeComponent
    ✓ should mock utils (11ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |       90 |      100 |    66.67 |      100 |                   |
 index.tsx |      100 |      100 |      100 |      100 |                   |
 utils.ts  |       50 |      100 |        0 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.589s, estimated 14s

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

关于javascript - Jest - 模拟一个函数被导入到你正在测试的组件文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58521281/

相关文章:

javascript - 将元素标题属性从同级克隆到 data-id

javascript - 无法读取未定义状态的属性

unit-testing - Windows 10 通用应用程序单元测试项目

unit-testing - 测试非不透明错误值

java - Arquillian JAVA EE 5 和 JBoss 4.2

javascript - 使用 jQuery 即时构建 HTML 表格

javascript - 使用javascript将时间戳添加到iframe中的src(防止缓存)

android - 使用 Espresso 测试 RxJava2 并在 suscribeOn 时出现空指针异常

javascript - sinon 试图监视 express res 对象

python - py.test : specifying python_files in the command line