玩笑测试为 eventemitter 对象发出事件(express)

Mr.*_*Mr. 4 javascript node.js express jestjs

试图从为 eventemitter 对象(http)发出事件的玩笑测试中获得灵感并没有解决我对express的痛苦。

\n\n

假设有以下nodejs代码

\n\n
// server.js\n\nconst express = require("express");\nconst app = express();\n\nconst server = app.listen(8080,\'127.0.0.1\')\n  .on("error", err => {\n    // ...\n  });\n\nmodule.exports = server;\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

我试过:

\n\n
// server.test.js\n\nit("should handle error", () => {\n  jest.mock("express", () => () => ({\n    listen: jest.fn().mockReturnThis(),\n    on: jest.fn().mockImplementationOnce((event, handler) => {\n      handler(new Error("network"));\n    })\n  }))\n  const express = require("express");\n  const app = express();\n  const appListenSpy = jest.spyOn(app, "listen")\n  require("./server");\n  expect(appListenSpy).toBeCalledTimes(1);\n  expect(app.listen).toBeCalledWith(8080,\'127.0.0.1\');\n  expect(app.on).toBeCalledWith("error", expect.any(Function));\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
 \xe2\x97\x8f server \xe2\x80\xba should handle listen error\n\n    expect(jest.fn()).toBeCalledTimes(expected)\n\n    Expected number of calls: 1\n    Received number of calls: 0\n\n    > 29 |     expect(appListenSpy).toBeCalledTimes(1);\n
Run Code Online (Sandbox Code Playgroud)\n

sli*_*wp2 5

更新jest.mock在每个测试用例中使用功能范围是可能的,但您应该在调用后导入/需要模块jest.mock()

\n

您不能jest.mock在函数范围内使用。它应该在模块范围内使用。您应该使用jest.doMock(moduleName,factory,options) ,而不是jest.mock在测试用例函数内部使用

\n

例如\n server.js

\n
const express = require(\'express\');\nconst app = express();\n\nconst server = app.listen(8080, \'127.0.0.1\').on(\'error\', (err) => {\n  console.log(err);\n});\n\nmodule.exports = server;\n
Run Code Online (Sandbox Code Playgroud)\n

server.test.js:

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

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

\n
 PASS  stackoverflow/60451082/server.test.js\n  60451082\n    \xe2\x9c\x93 should pass (19ms)\n\n  console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866\n    Error: network\n        at Object.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60451082/server.test.js:3:20)\n        at Object.asyncJestTest (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:100:37)\n        at resolve (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:43:12)\n        at new Promise (<anonymous>)\n        at mapper (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:26:19)\n        at promise.then (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:73:41)\n        at process._tickCallback (internal/process/next_tick.js:68:7)\n\n-----------|---------|----------|---------|---------|-------------------\nFile       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n-----------|---------|----------|---------|---------|-------------------\nAll files  |     100 |      100 |     100 |     100 |                   \n server.js |     100 |      100 |     100 |     100 |                   \n-----------|---------|----------|---------|---------|-------------------\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        4.444s, estimated 10s\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n