trying to get an inspiration from jest test emitting events for eventemitter objects (http) didn't solve my pain with express.
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;
how to write a test using jest to emit the http "error" event (to cover the error event handler)?
i tried:
// 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);