【问题标题】:Jest Node.js Not able to call beforeAll and afterAll properly using separate fileJest Node.js 无法使用单独的文件正确调用 beforeAll 和 afterAll
【发布时间】:2020-01-19 04:14:09
【问题描述】:

我在单独的文件bootstrap.js 中定义了beforAllafterAll,但我无法进行集成测试。我正在使用无服务器堆栈。我从 github 获得了帮助,但该示例是用 mocha 编写的,因此我尝试将其转换为玩笑。

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);
    });
});

我开玩笑的配置是

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.

【问题讨论】:

    标签: javascript node.js jestjs serverless-framework


    【解决方案1】:

    全局设置无法按您预期的方式工作。如果您看到日志,则您的 beforeAll 日志将在您的测试执行后出现。您应该使用不同的方式来设置和拆卸。 Jest 有globalSetupglobalTeardown 的概念,我想这更适合你的情况。作为其中的一部分,您可以启动和停止服务器。配置将如下所示

    在此处阅读更多信息 - https://jestjs.io/docs/en/configuration#globalsetup-string

    module.exports = {
        verbose: true,
        bail: true,
        coverageDirectory: 'output/coverage/jest',
        globalSetup: "./bootstrap.js",
        globalTeardown: "./bootstrap.js"
    };
    
    

    你的引导程序看起来像这样

    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);
        });
    };
    
    

    【讨论】:

    • 当我尝试使用 Promise 时,我遇到了这个问题:Timeout - Async callback was not invoked within the 30000ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 30000ms timeout specified by jest.setTimeout.
    • 你需要那个超时吗?不是,你可以删除它,否则你需要覆盖测试的默认超时以超过该值
    • 我已将此推送至github.com/bilalsha/sls-test-jest。你能看看吗。它也不适用于测试超时
    • 今天会看
    • @BilalShah - 你现在可以看看答案,看看它是否解决了你的问题。
    【解决方案2】:

    我在使用globalSetupglobalTeardown 的第一个答案的帮助下使用此配置解决了我的问题。

    在此处阅读更多信息 - https://jestjs.io/docs/en/configuration#globalsetup-string

    bootstrap.js

    const { spawn } = require('child_process');
    
    let slsOfflineProcess;
    
    module.exports = async () => {
        console.log('[Tests Bootstrap] Start');
        await startSlsOffline().catch((e) => {
            console.error(e);
            return;
        });
        global.__SERVERD__ = slsOfflineProcess;
    };
    
    function startSlsOffline() {
        slsOfflineProcess = slsOfflineProcess = spawn('sls', [ 'offline', 'start', '--port', 3005 ]);
    
        return finishLoading();
    }
    
    const finishLoading = () =>
        new Promise((resolve, reject) => {
            slsOfflineProcess.stdout.on('data', (data) => {
                if (data.includes('Serverless: Offline [HTTP] listening on')) {
                    console.log(data.toString().trim());
                    console.log(`Serverless: Offline started with PID : ${slsOfflineProcess.pid}`);
                    resolve('ok');
                }
    
                if (data.includes('address already in use')) {
                    reject(data.toString().trim());
                }
            });
    
            slsOfflineProcess.stderr.on('data', (errData) => {
                console.log(`Error starting Serverless Offline:\n${errData}`);
                reject(errData);
            });
        });
    
    
    teardown.js
    
    module.exports = async function() {
        let slsOfflineProcess = global.__SERVERD__;
        slsOfflineProcess.stdin.write('q\n');
        slsOfflineProcess.stdin.pause();
        await slsOfflineProcess.kill('SIGINT');
        console.log('Serverless Offline stopped');
    };
    

    在此链接上查找示例:https://github.com/bilalsha/sls-test-jest

    P.S globalTeardown 如果测试失败,则不起作用。找到后我会发布解决方案。

    【讨论】:

      猜你喜欢
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 2022-12-09
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      相关资源
      最近更新 更多