使用 Jest 模拟简单的内部函数以用于渲染的 React 组件

Cra*_*tis 2 javascript unit-testing mocking reactjs jestjs

我有一个简单的用下面的程序做出反应App.jsApp.test.jsutils.js文件:

应用程序.js

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

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

export default App;
Run Code Online (Sandbox Code Playgroud)

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()
});
Run Code Online (Sandbox Code Playgroud)

实用程序.js

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

Run Code Online (Sandbox Code Playgroud)

这是一个简单的示例,但我想要完成的是该randomNameGenerator()函数的 Jest 模拟,仅返回"Craig"特定 Jest test

我遵循了各种各样的教程/指南,但找不到任何有用的东西 - 我得到的最接近的(通过“感觉”)是这个(in 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';
    }),
  };
})
Run Code Online (Sandbox Code Playgroud)

它失败的方式是预期的:

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 | });
Run Code Online (Sandbox Code Playgroud)

El *_*mza 6

您可以通过调用来模拟模块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()
  });
});
Run Code Online (Sandbox Code Playgroud)