Jest 在测试中覆盖时不尊重 ENV 变量

问题描述 投票:0回答:2

我有一个看起来像这样的组件:

const isPersonalSite: boolean = process.env.PERSONAL_SITE === 'true';
const isFeatureEnabled: boolean = process.env.IS_FEATURE_ENABLED === 'true';

export const ProfileMenu = () => {
    console.log('PERSONAL_SITE component', process.env.PERSONAL_SITE)
    return (
        <>
            {!isPersonalSite && isFeatureEnabled &&
                <a href="http://test.com">Test 1</a>
            }

            {!isPersonalSite && !isFeatureEnabled &&
                <a href="http://test2.com">Test 2</a>
            }

            {isPersonalSite &&
                <a href="http://test3.com">Test 3</a>
            }

            <a href="/logout">Logout</a>
        </>
    )
}

我正在尝试使用 JestJS 编写一个测试。我的

jest.config.js
module.exports
之后包含以下定义:

process.env = Object.assign(process.env, {
    PERSONAL_SITE: false,
    IS_FEATURE_ENABLED: false
});

测试看起来像这样:

describe("ProfileDropDownMenu", () => {
    const env = process.env

    beforeEach(() => {
        jest.resetModules()
        process.env = { ...env }
    })
    
    afterEach(() => {
        process.env = env
    })
    
    it('render the menu', () => {
        process.env.PERSONAL_SITE = 'true'

        console.log('PERSONAL_SITE test', process.env.PERSONAL_SITE)
        
        render(
            <ProfileMenu />
        )
        
        expect(screen.getByText('Test 3')).toBeInDocument();
        expect(screen.getByText('Logout')).toBeInDocument();
    })
})

从上面来看,我希望测试能够通过,但它失败了,而是说文档中不存在

Test 3
,我想知道为什么。
PERSONAL_SITE test
打印出
true
PERSONAL_SITE component
也打印出
true
但是测试不会通过,为什么?

javascript reactjs jestjs
2个回答
0
投票

我认为问题是打字错误

.toBeInTheDocument()
而不是
.toBeInDocument()

我尝试了您提供的相同代码并通过了测试。

希望这有帮助


0
投票

isPersonalSite
isFeatureEnabled
在函数
ProfileMenu
之外声明。事实上,这两个 const 是在任何函数之外声明的。

这是什么意思?这意味着它们的值是在读取文件时计算的,因此在导入文件时计算的。

因此,当您拨打

ProfileMenu
时,
isPersonalSite
isFeatureEnabled
已设置为
true
/
false
(在本例中看起来是
false
)。

如何解决这个问题?有多种方法:

  1. 在函数内部设置两个常量的声明

    ProfileMenu

  2. 使用

    import()
    require()

    设置 process.env 后动态导入组件
  3. 使用 jest 设置文件,您可以在执行测试之前准备测试环境(全局模拟、全局环境变量):https://jestjs.io/docs/configuration#setupfiles-array

每种方法都有优点和缺点,具体取决于您想要实现的目标。我会避免第一个,因为您不应该编辑代码库来使测试通过,但在某些情况下,您可能需要以一种可以简化测试的方式进行编码。

© www.soinside.com 2019 - 2024. All rights reserved.