jest 测试为 eventemitter 对象发射事件(express) [英] jest test emitting events for eventemitter objects (express)

查看:14
本文介绍了jest 测试为 eventemitter 对象发射事件(express)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图从 为事件发射器对象 (http) 发射事件的玩笑测试 并没有解决我的express>.

trying to get an inspiration from jest test emitting events for eventemitter objects (http) didn't solve my pain with express.

假设下面的nodejs代码

assume the following nodejs code

// server.js

const express = require("express");
const app = express();

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

module.exports = server;

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

how to write a test using jest to emit the http "error" event (to cover the error event handler)?

我试过:

// server.test.js

it("should handle error", () => {
  jest.mock("express", () => () => ({
    listen: jest.fn().mockReturnThis(),
    on: jest.fn().mockImplementationOnce((event, handler) => {
      handler(new Error("network"));
    })
  }))
  const express = require("express");
  const app = express();
  const appListenSpy = jest.spyOn(app, "listen")
  require("./server");
  expect(appListenSpy).toBeCalledTimes(1);
  expect(app.listen).toBeCalledWith(8080,'127.0.0.1');
  expect(app.on).toBeCalledWith("error", expect.any(Function));
});

但是我在运行测试时得到了什么

but what i get when running the test

 ● server › should handle listen error

    expect(jest.fn()).toBeCalledTimes(expected)

    Expected number of calls: 1
    Received number of calls: 0

    > 29 |     expect(appListenSpy).toBeCalledTimes(1);

推荐答案

不能在函数作用域内使用 jest.mock.它应该在模块范围内使用.您应该使用 jest.mock="nofollow noreferrer">jest.doMock(moduleName, factory, options)

You can't use jest.mock in the function scope. It should be used in the module scope. Instead of using jest.mock inside the test case function, you should use jest.doMock(moduleName, factory, options)

例如server.js:

const express = require('express');
const app = express();

const server = app.listen(8080, '127.0.0.1').on('error', (err) => {
  console.log(err);
});

module.exports = server;

server.test.js:

describe('60451082', () => {
  it('should pass', () => {
    const mError = new Error('network');
    const appMock = {
      listen: jest.fn().mockReturnThis(),
      on: jest.fn().mockImplementationOnce((event, handler) => {
        handler(mError);
      }),
    };
    jest.doMock('express', () => jest.fn(() => appMock));
    const logSpy = jest.spyOn(console, 'log');
    const express = require('express');
    require('./server');
    expect(express).toBeCalledTimes(1);
    expect(appMock.listen).toBeCalledWith(8080, '127.0.0.1');
    expect(appMock.on).toBeCalledWith('error', expect.any(Function));
    expect(logSpy).toBeCalledWith(mError);
  });
});

100% 覆盖率的单元测试结果:

Unit test results with 100% coverage:

 PASS  stackoverflow/60451082/server.test.js
  60451082
    ✓ should pass (19ms)

  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/60451082/server.test.js:3: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:        4.444s, estimated 10s

源代码:https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60451082

这篇关于jest 测试为 eventemitter 对象发射事件(express)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆