用 Jest 模拟 dotenv

Mocking dotenv with Jest

我对最初使用 CRA 创建的 Web 应用程序进行了测试。所以它使用 Jest 和 react-testing-library。我也是在TypeScript环境下。

我的测试开始:

import { render, screen } from "@testing-library/react";
import dotenv from 'dotenv';
import App from './App';
. . . .
    jest.mock('dotenv');
//(what goes here?)

但这就是我需要帮助的地方。我不确定如何模拟模块。在组件中我有类似的东西:

if (process.env.REACT_APP_CONSTRUCTION === "true") {
    return (<UnderConstruction />);
} else {
    return (<App/ >);
}

在测试这个组件时,我想测试两种情况,一种是环境 returns “真”,另一种是其他情况。

想法或建议?

您可以在每次测试后开玩笑地创建模拟 env variables,如下所示。 此外,您不需要模拟 jest.mock('dotenv');,因此您可以在测试文件中删除该部分。

const OLD_ENV = process.env

afterEach(() => {
  cleanup()
  jest.clearAllMocks()
  jest.resetModules()
  process.env = { ...OLD_ENV }
  delete process.env.NODE_ENV
})

it('scenario 1', () => {
  // Given
  process.env.REACT_APP_CONSTRUCTION = true // mock variable for scenario 1

  // When
  const { queryByText } = render(<App />)
  const underConstructionText = queryByText('Under Construction')// Just an example

  // Then
  expect(underConstructionText).toBeInTheDocument()

})

it('scenario 2', () => {
  // Given
  process.env.REACT_APP_CONSTRUCTION = false // mock variable for scenario 2
  ...

  // When
  const { queryByText } = render(<App />)
  const underConstructionText = queryByText('Under Construction')
 
  // Then
  expect(underConstructionText).not.toBeInTheDocument()
})