嘲笑事件发射器对象的发射事件(http) [英] jest test emitting events for eventemitter objects (http)
问题描述
假设以下nodejs代码
assume the following nodejs code
const server = http.listen(8080,'127.0.0.1')
.on("error", err => {
// ...
})
module.exports = server;
如何使用笑话编写测试以发出http错误"事件(以覆盖错误事件处理程序)?
how to write a test using jest to emit the http "error" event (to cover the error event handler)?
推荐答案
由于您是在模块范围内创建服务器,因此在您require
或import
server.js
时,代码将立即执行.您需要先插入http.createServer
,然后才能使用此模块.
Since you create a server in module scope, the code will execute immediately when you require
or import
server.js
. You need to stub the http.createServer
before you require this module.
对于测试.on(error, callback)
方法,应该使用mockImplementation
或mockImplementationOnce
,因此,当模拟服务器调用模拟的.on('error', callback)
时,您将在测试用例中获得原始回调.这意味着handler
等同于callback
.当您调用handler(mError)
时,模拟的错误对象将被传递到原始的callback
中.然后,您可以使用此mError
测试您的代码逻辑.
For testing .on(error, callback)
method, you should use mockImplementation
or mockImplementationOnce
, so when the mocked server calls the mocked .on('error', callback)
, you will get the original callback in your test case. Which means handler
is equivalent to callback
. When you call handler(mError)
, the mocked error object will be passed into the original callback
. Then you can use this mError
test your code logic.
这是单元测试解决方案:
Here is the unit test solution:
server.js
:
const http = require('http');
const server = http.createServer();
server.listen(8080, '127.0.0.1').on('error', (err) => {
console.log(err);
});
module.exports = server;
server.test.js
:
const http = require('http');
describe('60435647', () => {
it('should handle error', () => {
const mError = new Error('network');
const mServer = {
listen: jest.fn().mockReturnThis(),
on: jest.fn().mockImplementationOnce((event, handler) => {
// handler is the original callback, the mError variable will be passed into the original callback.
handler(mError);
}),
};
const createServerSpy = jest.spyOn(http, 'createServer').mockImplementationOnce(() => mServer);
const logSpy = jest.spyOn(console, 'log');
require('./server');
expect(createServerSpy).toBeCalledTimes(1);
expect(mServer.listen).toBeCalledWith(8080, '127.0.0.1');
expect(mServer.on).toBeCalledWith('error', expect.any(Function));
expect(logSpy).toBeCalledWith(mError);
});
});
单元测试结果覆盖率100%:
Unit test results with 100% coverage:
PASS stackoverflow/60435647/server.test.js
60435647
✓ should handle error (459ms)
console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866
Error: network
at Object.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60435647/server.test.js:5:20)
at Object.asyncJestTest (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:100:37)
at resolve (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:43:12)
at new Promise (<anonymous>)
at mapper (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
at promise.then (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:73:41)
at process._tickCallback (internal/process/next_tick.js:68:7)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
server.js | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.772s, estimated 6s
这篇关于嘲笑事件发射器对象的发射事件(http)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!