javascript - Jest 测试为 eventemitter 对象发出事件 (http)

标签 javascript node.js jestjs

假设以下nodejs代码

const server = http.listen(8080,'127.0.0.1')
  .on("error", err => {
    // ...
  })

module.exports = server;

如何使用 jest 编写测试来发出 http“错误”事件(以覆盖错误事件处理程序)?

最佳答案

由于您在模块范围内创建了服务器,因此当您 requireimport server.js 时,代码将立即执行。在需要此模块之前,您需要 stub http.createServer

为了测试.on(error,callback)方法,你应该使用mockImplementationmockImplementationOnce,这样当被模拟的服务器调用被模拟的服务器时.on('error', callback),您将在测试用例中获得原始回调。这意味着handler相当于callback。当您调用handler(mError)时,模拟的错误对象将被传递到原始回调中。然后你可以使用这个mError测试你的代码逻辑。

这是单元测试解决方案:

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%覆盖率的单元测试结果:

 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

关于javascript - Jest 测试为 eventemitter 对象发出事件 (http),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60435647/

相关文章:

javascript - 关联图像未在缩略图列表中放大

node.js - 如何在 docker-compose.yaml 中填充卷

javascript - 工厂尝试创建两个具有相同属性的对象

javascript - 语法错误 : Cannot use import statement outside a module: when running Jest-expo tests

reactjs - 使用 setTimeout 进行 Jest 测试 Hook 状态更新

javascript - Jquery UI 可拖动在屏幕底部创建一个空白

javascript - 做循环,直到数组中的元素在 Javascript 中为空

javascript - 使用 chrome 扩展将文件从本地存储上传到服务器

javascript - 如何在 Visual Studio Code 中调试从 Grunt 运行的 Jasmine 测试?

node.js - NPM 包版本错误,Mocha 未知选项 --exit