我的 Jest 测试之一是生成一个新进程来运行服务器,这将充当启动测试。我想将环境变量传递给新进程。
注意:以下测试在 GitLab CI 上运行,无需设置环境变量,以避免 CI 与测试耦合。
下面的代码有什么问题?
process.env.HOST = 'localhost';
process.env.DATABASE = 'my_db';
process.env.USERNAME = 'my_admin';
process.env.PASSWORD = 'my_passwd123';
describe('STARTUP: test', () => {
let app: ChildProcess;
const url = 'http://0.0.0.0:3000/';
beforeAll(async () => {
app = spawn('node', ['index.js']);
await new Promise(resolve => {
setTimeout(resolve, 8000);
});
});
afterAll(() => {
app.kill();
});
it('should return when calling /health', async () => {
const response = await axios.get(url);
expect(response.status).toBe(200);
});
});
我找到的解决方案:
jest.config.js
属性setupFiles
module.exports = {
testMatch: ['**/tests/**/startup.test.ts'],
testTimeout: 15000,
setupFiles: ['<rootDir>/startupEnvVars.js'],
};
startupEnvVars.js
变量创建了 env
文件process.env.HOST = 'localhost';
process.env.DATABASE = 'my_db';
process.env.USERNAME = 'my_admin';
process.env.PASSWORD = 'my_passwd123';
env
变量并确保 process.env
复制到新进程。describe('STARTUP: test', () => {
let app: ChildProcess;
const url = 'http://0.0.0.0:3000/';
beforeAll(async () => {
app = spawn('node', ['index.js'], {
detached: true,
stdio: 'inherit',
shell: true,
env: {
...process.env,
},
});
await new Promise(resolve => {
setTimeout(resolve, 8000);
});
});
afterAll(() => {
app.kill();
});
it('should return when calling /health', async () => {
const response = await axios.get(url);
expect(response.status).toBe(200);
});
});