我已在单独的文件 bootstrap.js
中定义了 beforAll
和 afterAll
,但我无法进行集成测试。我正在使用无服务器堆栈。我从 github 获得了帮助,但该示例是用 mocha 编写的,因此我尝试将其转换为 jest。
bootstrap.js
beforeAll(async () => {
console.log('[Tests Bootstrap] Start');
await startSlsOffline((err) => {
if (err) {
console.log(err);
}
console.log('[Tests Bootstrap] Done');
});
}, 30000);
afterAll(async () => {
console.log('[Tests Teardown] Start');
await stopSlsOffline();
console.log('[Tests Teardown] Done');
});
handler.test.js
describe('get Endpoints', () => {
const server = request(`http://localhost:3005`);
test('should run get example', async () => {
const res = await server.get('/example');
console.log('res', res.body);
});
});
我的 Jest 配置是
module.exports = {
verbose: true,
bail: true,
coverageDirectory: 'output/coverage/jest',
setupFilesAfterEnv: [ './bootstrap.js' ]
};
我得到的输出是
> jest --config test/jest.config.js
FAIL test/handler.test.js
get Endpoints
✕ should run get example (38ms)
● get Endpoints › should run get example
connect ECONNREFUSED 127.0.0.1:3005
console.log test/bootstrap.js:6
[Tests Bootstrap] Start
console.log test/bootstrap.js:30
Serverless: Offline started with PID : 5587 and PORT: 3005
console.log test/bootstrap.js:18
[Tests Teardown] Start
console.log test/bootstrap.js:47
Serverless Offline stopped
console.log test/bootstrap.js:22
[Tests Teardown] Done
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 2.825s
Ran all test suites.
npm ERR! Test failed. See above for more details.
最佳答案
全局设置没有按照您期望的方式工作。如果您看到日志,则表明您的 beforeAll 日志将在测试执行后出现。您应该使用不同的方式来设置和拆卸。 Jest 有 globalSetup
和 globalTeardown
的概念,我想这更适合您的情况。作为此过程的一部分,您可以启动和停止服务器。配置将如下所示
在此处了解更多信息 - https://jestjs.io/docs/en/configuration#globalsetup-string
module.exports = {
verbose: true,
bail: true,
coverageDirectory: 'output/coverage/jest',
globalSetup: "./bootstrap.js",
globalTeardown: "./bootstrap.js"
};
你的 Bootstrap 将如下所示
const { spawn} = require('child_process');
let slsOfflineProcess;
module.exports = async () => {
console.log('[Tests Bootstrap] Start');
await startSlsOffline((err) => {
if (err) {
console.log(err);
}
console.log('[Tests Bootstrap] Done');
});
}
const startSlsOffline = (done) => {
if (slsOfflineProcess) {
slsOfflineProcess.kill('SIGINT');
console.log('Serverless Offline stopped');
done();
}
slsOfflineProcess = spawn('sls', [ 'offline', 'start', '--port', 3005 ]);
console.log(`Serverless: Offline started with PID : ${slsOfflineProcess.pid} and PORT: 3005`);
slsOfflineProcess.stdout.on('data', (data) => {
if (data.includes('Offline listening on')) {
console.log(data.toString().trim());
done();
}
});
slsOfflineProcess.stderr.on('data', (errData) => {
console.log(`Error starting Serverless Offline:\n${errData}`);
done(errData);
});
};
关于javascript - Jest Node.js 无法使用单独的文件正确调用 beforeAll 和 afterAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59676343/