Javascript jest测试为eventemitter对象发出事件(express)

Javascript jest测试为eventemitter对象发出事件(express),javascript,node.js,express,jestjs,Javascript,Node.js,Express,Jestjs,试图从中获得灵感并不能解决我的痛苦 假设下面的nodejs代码 //server.js const express=要求(“express”); 常量app=express(); const server=app.listen(8080,'127.0.0.1') .on(“错误”,err=>{ // ... }); module.exports=服务器; 如何使用jest编写测试以发出http“错误”事件(覆盖错误事件处理程序) 我试过: //server.test.js 它(“应该处理错误”

试图从中获得灵感并不能解决我的痛苦

假设下面的nodejs代码

//server.js
const express=要求(“express”);
常量app=express();
const server=app.listen(8080,'127.0.0.1')
.on(“错误”,err=>{
// ...
});
module.exports=服务器;
如何使用jest编写测试以发出http“错误”事件(覆盖错误事件处理程序)

我试过:

//server.test.js
它(“应该处理错误”,()=>{
开玩笑。模仿(“快车”,()=>()=>({
听:jest.fn().mockReturnThis(),
on:jest.fn().mockImplementationOnce((事件,处理程序)=>{
处理程序(新错误(“网络”);
})
}))
const express=要求(“express”);
常量app=express();
const appListenSpy=jest.spyOn(应用程序,“监听”)
要求(“/服务器”);
期望(appListenSpy)。等待调用时间(1);
期望(app.listen).toBeCalledWith(8080,'127.0.0.1');
expect(app.on).toBeCalledWith(“error”,expect.any(Function));
});
但是我在运行测试时得到了什么

● 服务器›应处理侦听错误
expect(jest.fn()).tobeCalledTime(预期)
预期呼叫数:1
收到的呼叫数:0
>29 |期望(应用检验)。被催缴的时间(1);

您不能在函数范围中使用
jest.mock
。它应该在模块范围内使用。您不应该在测试用例函数中使用
jest.mock
,而应该使用

例如。
server.js

const express=require('express');
常量app=express();
const server=app.listen(8080,'127.0.0.1')。on('error',(err)=>{
控制台日志(err);
});
module.exports=服务器;
server.test.js

description('60451082',()=>{
它('应该通过',()=>{
const mError=新错误(“网络”);
常量appMock={
听:jest.fn().mockReturnThis(),
on:jest.fn().mockImplementationOnce((事件,处理程序)=>{
handler(mError);
}),
};
jest.doMock('express',()=>jest.fn(()=>appMock));
constlogspy=jest.spyOn(控制台,'log');
const express=require('express');
需要('./服务器');
期望(快速)。等待时间(1);
expect(appMock.listen).toBeCalledWith(8080,'127.0.0.1');
expect(appMock.on).toBeCalledWith('error',expect.any(Function));
expect(logSpy).与(mError)一起调用;
});
});
100%覆盖率的单元测试结果:

PASS stackoverflow/60451082/server.test.js
60451082
✓ 应通过(19ms)
console.log node_modules/jest environment/node_modules/jest mock/build/index.js:866
错误:网络

在Object。

非常感谢您的帮助。当我运行测试时,它在
expect(express)上失败由于
收到的呼叫数:0
。我正在试图找出原因。你能评论一下如何让mock
appMock.on()
返回这个,这样其他链接的
on()
调用就可以工作了吗?mock破坏了其他测试,所以我试着把
放在每个(()=>{jest.clearalmocks();jest.resetAllMocks();}
但这没有帮助。你能给我一个线索吗?在一篇文章中创建了一个跟进问题