gpt4 book ai didi

javascript - 异步 Jasmine 测试在操作之前不会调用 beforeEach()

转载 作者:行者123 更新时间:2023-11-28 20:50:18 24 4
gpt4 key购买 nike

我正在尝试为我的客户端-服务器模块编写测试代码。我需要在客户端发送请求之前运行服务器,因此我尝试使用 beforeEach,但在服务器开始运行之前测试就失败了。

我的测试:

'use strict';
const cp = require('child_process');
const ip = require('my-local-ip');
const utils = require('../util/utils');

describe('Server and client connectivity:', () => {

let originalTimeout;
let server;

beforeEach(function() {
server = cp.fork('Server/Server');
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
});

it('should transfer index.html file to client', (done) => {
const client = cp.fork('Client/request', ['-t', ip(), '-p', 3300]);
expect(utils.isFileExistsInDirectory('Client/', 'index.html')).toBe(true);
done();
});

afterEach(function() {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});

});

当我首先手动运行服务器,然后使用这些命令运行客户端时,它工作得很好。

在测试中,有时客户端请求在服务器监听之前发送。
怎么会这样?
我做错了什么?

最佳答案

在当前的实现中,您正在 fork 服务器进程,但不会等到服务器实际启动。

为了解决这个问题,我们需要设置一些进程间通信。在使用 fork 的情况下,使用 .send.on 很容易做到,因为:

The returned ChildProcess will have an additional communication channel built-in that allows messages to be passed back and forth between the parent and child...

根据 the doc .

请看例子server.js:

// A simple server
const express = require('express');

const app = express();
app.get('/', (req, res) => res.json({message: 'ok'}));

app.listen(8080, () => {
// This function exists only if this is a child process
if (process.send) {
// Telling the parent that the server is launched
process.send('launched');
}

console.log('Server started');
});

spec.js:

const child_process = require('child_process');
const request = require('request');
const assert = require('assert');

describe('Connectivity with forked server', () => {
let server;

beforeAll(done => {
server = child_process.fork('server.js');

// Wait for the message from a child server before running any tests
server.on('message', data => {
if (data === 'launched') {
console.log('Before block executed');
done();
}
});
});

// Killing the server after all the tests
afterAll(() => server.kill('SIGTERM'));

it('should be able to interact with server', done => {
request({url: 'http://localhost:8080', json: true}, (err, resp, body) => {
if (err) {
return done(err);
}

assert.equal(body.message, 'ok');

console.log('test executed');
done();
});
});
});

我使用了 beforeAllafterAll 而不是 beforeEach 但如果需要你可以切换回 beforeEach .

此外,我还设置了一些逻辑以在执行测试后关闭进程。

关于javascript - 异步 Jasmine 测试在操作之前不会调用 beforeEach(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49834035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com