我有一个来自最初使用CRA创建的web应用程序的测试。所以它使用了Jest和react测试库。我也在一个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/ >);
}在测试这个组件时,我想测试两种场景,一种是环境返回"true“,另一种则不然。
想法还是建议?
发布于 2020-07-05 08:40:06
您可以在每次测试后创建模拟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()
})https://stackoverflow.com/questions/62731786
复制相似问题