zjsunit: Lift restriction against mocking CJS modules.

Factor out mock_cjs from mock_esm because adding __esModule prevents
mocks for CJS modules from being imported correctly.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2021-03-11 23:55:38 -08:00
parent 876806eb4d
commit 5251fa81fb
1 changed files with 8 additions and 6 deletions

View File

@ -30,11 +30,7 @@ exports.start = () => {
Module._load = load;
};
exports.mock_esm = (request, obj = {}) => {
if (typeof obj !== "object") {
throw new TypeError("An ES module must be mocked with an object");
}
exports.mock_cjs = (request, obj) => {
const filename = Module._resolveFilename(
request,
require.cache[callsites()[1].getFileName()],
@ -49,11 +45,17 @@ exports.mock_esm = (request, obj = {}) => {
throw new Error(`It is too late to mock ${filename}; call this earlier.`);
}
obj.__esModule = true;
module_mocks.set(filename, obj);
return obj;
};
exports.mock_esm = (request, obj = {}) => {
if (typeof obj !== "object") {
throw new TypeError("An ES module must be mocked with an object");
}
return exports.mock_cjs(request, {...obj, __esModule: true});
};
exports.unmock_module = (request) => {
const filename = Module._resolveFilename(
request,