gpt4 book ai didi

node.js - 在 Jest 中创建 IncomingMessage 测试虚拟机

转载 作者:行者123 更新时间:2023-12-05 03:41:10 25 4
gpt4 key购买 nike

我正在尝试为将 IncomingMessage 作为参数的函数编写单元测试。我知道这是一个流,但我不确定如何创建一个基本的测试虚拟机,因为该流导致我的测试超时

: Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:

我的类(class)

import { IncomingMessage } from 'http';

export class MyClass
example(request: IncomingMessage): void {
console.log(request.get('hello?'))
}
}

我的测试

it('test', () => {
const myclass = new MyClass();

const request = {
get: () => 'hello!'
} as unknown as IncomingMessage

const response = myclass.example(request);

expect(response).toEqual('hello!');
});

我假设我需要关闭流,那么在将“虚拟”对象转换为键入 IncomingMessage 时我该怎么做?

我试过用

const request = {
get: () => 'hello'
} as unknown as IncomingMessage
request.setTimeout(1)

但随后我得到一个错误,指出找不到该函数,这是有道理的,因为虚拟对象基本上是一个只有一个模拟函数的空对象

TypeError: request.setTimeout is not a function

在这种情况下,我假设我需要实际创建一个真正的 IncomingMessage?但是我找不到太多关于如何执行此操作的文档或示例

创建真正的 IncomingMessage 流、快速关闭它并使用模拟的 get 方法的最佳方法是什么?我想我需要模拟套接字吗?

或者在这种情况下测试我的类和函数的正确方法是什么?

最佳答案

基本上你需要模拟你的请求对象,可以用下面的代码片段来完成:

function _mock_req() {
let req = {
get: jest.fn(() => 'hello!'),
};
return req;
}

模拟完成后,在您的测试用例中调用它,这里我使用 beforeEach 来解决问题:openHandler- Async callback was not invoked

describe('http test', () => {
let req, res;
const myclass = new MyClass();

beforeEach((done) => {
req = _mock_req();
res = myclass.example(req);
done();
});

it('class test', () => {
expect(res).toEqual('hello!');
});
});

您还需要从您的类(class)返回request 以测试通过。在执行测试用例时,您的模拟请求对象将从 MyClass

返回
export class MyClass {
example(request: IncomingMessage): void {
console.log(request.get('hello?'));
return request.get('hello?')
}
}

测试用例结果:

enter image description here

关于node.js - 在 Jest 中创建 IncomingMessage 测试虚拟机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67866999/

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