javascript - 使用 Jest 模拟简单的内部函数以在渲染的 React 组件中使用

标签 javascript reactjs unit-testing mocking jestjs

我有一个简单的 React 应用程序,包含以下 App.jsApp.test.jsutils.js 文件:

App.js

import React from 'react';
import { randomNameGenerator } from './utils.js';
import './App.css';

function App() {
  return (
    <div>
      {randomNameGenerator()}
    </div>
  );
}

export default App;

App.test.js

import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect'
import App from './App';

it('allows Jest method mocking', () => {
  const { getByText } = render(<App />);
  expect(getByText("Craig")).toBeInTheDocument()
});

utils.js

export function randomNameGenerator() {
    return Math.floor((Math.random() * 2) + 1) == 1 ? 'Steve' : 'Bill';
}

这是一个简单的例子,但我试图完成的是 randomNameGenerator() 函数的 Jest 模拟,它只返回 “Craig” 用于特定的 Jest 测试

我遵循了各种各样的教程/指南,但找不到任何有用的东西 - 我得到的最接近(“感觉”)的是这个(在 App.test.js),这没有效果:

jest.doMock('./utils', () => {
  const originalUtils = jest.requireActual('./utils');
  return {
    __esModule: true,
    ...originalUtils,
    randomNameGenerator: jest.fn(() => {
      console.log('## Returning mocked typing duration!');
      return 'Craig';
    }),
  };
})

它失败的方式是预期的:

Unable to find an element with the text: Craig. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

    <body>
      <div>
        <div>
          Steve
        </div>
      </div>
    </body>

       6 | it('allows Jest method mocking', () => {
       7 |   const { getByText } = render(<App />);
    >  8 |   expect(getByText("Craig")).toBeInTheDocument()
         |          ^
       9 | });

最佳答案

您可以通过调用 jest.mock 来模拟模块,然后导入它,然后在您的测试中调用 mockImplementation 来设置正确的返回值。

import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect'
import App from './App';

import { randomNameGenerator } from "./utils";

jest.mock('./utils.js', () => ({ 
  randomNameGenerator: jest.fn()
}));

describe('test', () => {
  it('allows Jest method mocking 1', () => {
    randomNameGenerator.mockImplementation(() => "Craig");
    const { getByText } = render(<App />);
    expect(getByText("Craig")).toBeInTheDocument()
  });

  it('allows Jest method mocking 2', () => {
    randomNameGenerator.mockImplementation(() => "Not Craig");
    const { getByText } = render(<App />);
    expect(getByText("Not Craig")).toBeInTheDocument()
  });
});

关于javascript - 使用 Jest 模拟简单的内部函数以在渲染的 React 组件中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209173/

相关文章:

javascript - 对象未按预期呈现

javascript - HTML Bootstrap 边框/面板

javascript - 在 jQuery 中处理 Bootstrap 下拉事件

reactjs - 在 react-Native 中创建 UI 时 Class 和 Const 有什么区别?

unit-testing - 如何在 Jest 中测试从构造函数调用然后调用其他异步函数的 init() 函数

unit-testing - Angular 2 单元测试可观察到的错误 (HTTP)

java - SpringBoot : How ReflectionTestUtils. setFields 工作吗?

javascript - 创建水平菜单 Web 应用程序

javascript - Excel SelectionChanged 事件未触发

javascript - 尝试使用 React + TypeScript 项目修复 tslint 错误