【问题标题】:Partially mock React module with Jest用 Jest 部分模拟 React 模块
【发布时间】:2019-08-15 01:29:52
【问题描述】:

我试图在导入的 React 模块中只模拟一个函数,保持模块的其余部分不被模拟,并在所有测试的顶层执行此操作。

我正在使用新的 create-react-app 项目和单个测试来观察问题。

重现步骤:

  • create-react-app test
  • 使用提供的src/App.test.js 作为唯一的测试文件
  • npm run test

App.test.js

jest.mock('react', () => {
  jest.dontMock('react');

  const React = require('react');
  const lazy = jest.fn();

  return {
    ...React,
    lazy
  };
});

import * as React from 'react';
const React2 = require('react');

it('should partially mock React module', async () => {
  expect(jest.isMockFunction(React.lazy)).toBe(true); // passes
  expect(jest.isMockFunction(React2.lazy)).toBe(true); // fails
  expect(jest.isMockFunction(require('react').lazy)).toBe(true); // fails
  expect(jest.isMockFunction((await import('react')).lazy)).toBe(true); // fails
});

这里的问题似乎是jest.dontMock,因为它可以防止require 和动态import 被模拟,但仍不清楚为什么可以以这种方式模拟静态import,因为它使用require反正。这是转译文件:

"use strict";

jest.mock('react', () => {
  jest.dontMock('react');

  const React = require('react');

  const lazy = jest.fn();
  return (0, _objectSpread2.default)({}, React, {
    lazy
  });
});

var _interopRequireWildcard3 = require("...\\node_modules\\@babel\\runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("...\\node_modules\\@babel\\runtime/helpers/interopRequireDefault");

var _interopRequireWildcard2 = _interopRequireDefault(require("...\\node_modules\\@babel\\runtime/helpers/interopRequireWildcard"));

var _objectSpread2 = _interopRequireDefault(require("...\\node_modules\\@babel\\runtime/helpers/objectSpread"));

var React = _interopRequireWildcard3(require("react"));

const React2 = require('react');
...

这可能与 create-react-app Jest+Babel 设置有关,因为我无法使 jest.dontMock 与 vanilla Jest 和 require 一起正常工作。

为什么静态 React import 被嘲笑,而 React2 和其他的不是?里面到底发生了什么?

如何修复jest.dontMock 当前行为以在顶层部分模拟模块?

【问题讨论】:

  • 我认为require.requireActual 应该做到issue 中提到的技巧。这个也不需要jest.dontMock('react')。我不知道为什么 dontMock 对于 import 和 require 的行为不同 - 它应该防止在这两种情况下进行模拟。
  • @AWolf 我知道 requireActual 但完全忘记了它,并且在您链接的问题中以某种方式忽略了它。确实,这就是解决方案,谢谢。如果您愿意,可以考虑提供此修复作为答案。

标签: javascript reactjs jestjs create-react-app babel-jest


【解决方案1】:

默认导入:

一个简单的解决方案是在setupTest.js 中模拟React.lazy

import React from 'react';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });

jest.spyOn(React.lazy);

react 中的任何后续 require/imports 都将针对每个测试文件进行部分模拟。

工作示例https://github.com/mattcarlotta/react-lazy-mocked(我不使用create-react-app,但jest可以像我一样设置)

安装:

  • git clone git@github.com:mattcarlotta/react-lazy-mocked.git
  • cd react-lazy-mocked
  • yarn install
  • yarn test

root/__tests__/root.test.js

import React from 'react';
import App from '../index.js';

const React2 = require('react');

describe('App', () => {
  const wrapper = mount(<App />);

  it('renders without errors', () => {
    const homeComponent = wrapper.find('.app');
    expect(homeComponent).toHaveLength(1);
  });

  it('should partially mock React module', async () => {
    expect(jest.isMockFunction(await require('react').lazy)).toBe(true); // eslint-disable-line global-require
    expect(jest.isMockFunction(React)).toBe(false);
    expect(jest.isMockFunction(React.lazy)).toBe(true);
    expect(jest.isMockFunction(React2)).toBe(false);
    expect(jest.isMockFunction(React2.lazy)).toBe(true);
  });

  it('should no longer be partially mocked within the test file', () => {
    React.lazy.mockRestore();
    expect(jest.isMockFunction(React.lazy)).toBe(false);
  });
});

pages/Home/__tests__/Home.test.js

import React from 'react';
import Home from '../index.js';

describe('Home', () => {
  const wrapper = shallow(<Home />);

  it('renders without errors', () => {
    const homeComponent = wrapper.find('.app');
    expect(homeComponent).toHaveLength(1);
  });

  it('should partially mock React module', async () => {
    expect(jest.isMockFunction(React.lazy)).toBe(true);
  });
});

命名导入:

工作示例https://github.com/mattcarlotta/named-react-lazy-mocked

安装:

  • git clone git@github.com:mattcarlotta/named-react-lazy-mocked.git
  • cd named-react-lazy-mocked
  • yarn install
  • yarn test

utils/__mocks__/react.js

jest.mock('react', () => ({
  ...require.requireActual('react'),
  lazy: jest.fn(),
}));
module.exports = require.requireMock('react');

utils/setup/setupTest.js(可选地,您可以将模拟的react 文件添加为global jest 函数,这样您就不必为每个测试编写import * as React from 'react' ):

import { JSDOM } from 'jsdom';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
// import React from '../__mocks__/react';

configure({ adapter: new Adapter() });

// global.React = React;

root/__tests__/root.test.js

import * as React from 'react';
import App from '../index.js';

const React2 = require('react');

describe('App', () => {
  const wrapper = mount(<App />);

  it('renders without errors', () => {
    const homeComponent = wrapper.find('.app');
    expect(homeComponent).toHaveLength(1);
  });

  it('should partially mock React module', async () => {
    expect(jest.isMockFunction(await require('react').lazy)).toBe(true); // eslint-disable-line global-require
    expect(jest.isMockFunction(React)).toBe(false);
    expect(jest.isMockFunction(React.lazy)).toBe(true);
    expect(jest.isMockFunction(React2)).toBe(false);
    expect(jest.isMockFunction(React2.lazy)).toBe(true);
  });
});

【讨论】:

  • 感谢您的详细解答。可悲的是,这不适用于我的情况,因为问题是模拟命名导入。默认import React from 'react' 可能会更简单,但我没有使用它。 React 导入最常用作import React, { lazy } from 'react',其中React 默认导出仅由 Babel/TS 用于为 JSX 转换提供React.createElement
  • 你的意思是像import * as React from 'react'; React.lazy = jest.fn()这样的东西吗?由于 Babel 的 ES 模块互操作如何为 * 工作,这将不起作用。
  • 为命名导出找到了答案。更新了答案以包含两者。
  • 谢谢,我现在就是这样做的。
猜你喜欢
  • 2017-02-23
  • 2019-12-26
  • 2021-09-07
  • 1970-01-01
  • 2019-08-17
  • 2021-02-04
  • 2017-12-09
  • 1970-01-01
相关资源
最近更新 更多