esmock: Partial mocking not working as expected

Hi, I’m trying to partially mock an imported module, but esmock seems to mock the whole module so that functions which I don’t want to mock are not available.

app.js:

import express from "express";
import passport from "passport";

const app = express();
const bearerOptions = { ... };

passport.use(bearerStrategy);
app.use(passport.initialize());

app.test.js:

import chai from "chai";
import chaiHttp from "chai-http";
import esmock from "esmock";

chai.use(chaiHttp);
chai.should();

const app = await esmock(
	"../src/app.js",
	{
		passport: {
			use: function (bearerStrategy) {
				console.log(bearerStrategy);
			},
		},
	},
	{}
);

describe("/", function () {
	it("should work", (done) => {
		try {
			chai
				.request(app.default)
				.get("/")
				.end((err, res) => {
					try {
						res.should.have.status(200);
					} catch (err) {
						console.error(res.text);
						throw err;
					}
					done();
				});
		} catch (e) {
			console.log(e);
		}
	});
});

Expected result: Output from mocked passport.use method and call of original passport.initialize method

Actual result: TypeError: passport.initialize is not a function at file:///C:/../src/app.js?esmk=1:9:18 at ModuleJob.run (node:internal/modules/esm/module_job:193:25) at async Promise.all (index 0) at async ESMLoader.import (node:internal/modules/esm/loader:530:24) at async file:///C:/.../node_modules/esmock/src/esmock.js:3:176 at async file:///C:/.../tests/app.test.js:11:13

What am I doing wrong here?

Thanks!

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 18 (10 by maintainers)

Most upvoted comments

I would love to help more, but I am quite busy.