如何动态设置 testEnvironment: ‘node’ 配置

huangapple go评论131阅读模式
英文:

How to set testEnvironment: 'node' config dynamically

问题

我最初在我的NextJS应用中的src/tests/components/*.test.tsx目录下编写了一堆用jest编写的测试。现在我正在尝试编写我的第一个端到端测试,位于src/tests/end-to-end/*.test.tsx目录下。

我遇到了运行这两种类型的测试一起的问题,因为它们需要不同的测试环境配置。对于组件测试,我需要使用testEnvironment: 'jest-environment-jsdom',但对于端到端测试,我需要使用testEnvironment: 'node'

是否有办法在运行端到端测试时将测试环境设置为node?如何最好地设置这个?

英文:

I initially had a bunch of tests written in jest for my NextJS app located in src/tests/components/*.test.tsx. I'm now trying to write my first end-to-end tests under src/tests/end-to-end/*.test.tsx.

I'm having issues running both types of tests together as they require different test environment configurations. For the component tests, I need to use testEnvironment: 'jest-environment-jsdom', but for the end-to-end tests, I need to use testEnvironment: 'node'.

Is there a way for me to set the test environment to node but only when running the E2E tests? What's the best way to set this up?

答案1

得分: 1

是的,一个想法是使用一个节点信封文件,可以存储你所处的环境。
在使用npm安装dotenv后,你可以在你的仓库根目录下创建一个.env文件。

在文件中添加:ENVIRONMENT=prod

然后在你需要引用变量的文件中,按照以下方式操作。
例如:

require("dotenv").config();
const obj = {
    testEnvironment: process.env.ENVIRONMENT === 'prod' ? 'node' : 'otherSetting'
}

请注意,以上代码中的注释不会被翻译。

英文:

Yes one idea is to use a node envelope file that can store what env you are in.
After installing dotenv with npm i dotenv, you create a .env file at the root of your repo.

In the file add: ENVIRONMENT=prod

Then in the file you need to reference your variable, follow as below.
ex.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

require(&quot;dotenv&quot;).config();
const obj = {
    testEnvironment: process.env.ENVIRONMENT === &#39;prod&#39; ? &#39;node&#39; : &#39;otherSetting&#39;
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月15日 23:54:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483453.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定