Load nodejs module dynamically with mocked filesystem in jest unit tests? - javascript

Well I'm trying to unit test a module loading script. Part of it is of course creating mocks for the scripts. For this mock-fs library is used.
import mock = require("mock-fs");
describe("getFileConfig", function () {
beforeEach(() => {
jest.resetModules();
});
afterEach(() => {
mock.restore();
});
it("should read and parse .js from ./config", async () => {
const expected = {
abc: 1,
fun: function() {return true;}
};
mock({config: {"myCfg.js": "module.exports = {abc: 1, fun: function(){return true;}}"}});
const test = require("./config/myCfg.js");
expect(test.abc).toEqual(1);
});
});
I "think" this should work? - mock creates a local copy of the file systems right?
However when I test above test the following error occurs:
Error: Cannot find module './config/myCfg.js' from 'test/loader.test.ts'
So this means the module loader is not using the mocked filesystem? How can make it use the mocked filesystem?

Related

Mocking node_modules which return a function with Jest?

I am writing a typeScript program which hits an external API. In the process of writing tests for this program, I have been unable to correctly mock-out the dependency on the external API in a way that allows me to inspect the values passed to the API itself.
A simplified version of my code that hits the API is as follows:
const api = require("api-name")();
export class DataManager {
setup_api = async () => {
const email = "email#website.ext";
const password = "password";
try {
return api.login(email, password);
} catch (err) {
throw new Error("Failure to log in: " + err);
}
};
My test logic is as follows:
jest.mock("api-name", () => () => {
return {
login: jest.fn().mockImplementation(() => {
return "200 - OK. Log in successful.";
}),
};
});
import { DataManager } from "../../core/dataManager";
const api = require("api-name")();
describe("DataManager.setup_api", () => {
it("should login to API with correct parameters", async () => {
//Arrange
let manager: DataManager = new DataManager();
//Act
const result = await manager.setup_api();
//Assert
expect(result).toEqual("200 - OK. Log in successful.");
expect(api.login).toHaveBeenCalledTimes(1);
});
});
What I find perplexing is that the test assertion which fails is only expect(api.login).toHaveBeenCalledTimes(1). Which means the API is being mocked, but I don't have access to the original mock. I think this is because the opening line of my test logic is replacing login with a NEW jest.fn() when called. Whether or not that's true, I don't know how to prevent it or to get access to the mock function-which I want to do because I am more concerned with the function being called with the correct values than it returning something specific.
I think my difficulty in mocking this library has to do with the way it's imported: const api = require("api-name")(); where I have to include an opening and closing parenthesis after the require statement. But I don't entirely know what that means, or what the implications of it are re:testing.
I came across an answer in this issue thread for ts-jest. Apparently, ts-jest does NOT "hoist" variables which follow the naming pattern mock*, as regular jest does. As a result, when you try to instantiate a named mock variable before using the factory parameter for jest.mock(), you get an error that you cannot access the mock variable before initialization.
Per the previously mentioned thread, the jest.doMock() method works in the same way as jest.mock(), save for the fact that it is not "hoisted" to the top of the file. Thus, you can create variables prior to mocking out the library.
Thus, a working solution is as follows:
const mockLogin = jest.fn().mockImplementation(() => {
return "Mock Login Method Called";
});
jest.doMock("api-name", () => () => {
return {
login: mockLogin,
};
});
import { DataManager } from "../../core/dataManager";
describe("DataManager.setup_api", () => {
it("should login to API with correct parameters", async () => {
//Arrange
let manager: DataManager = new DataManager();
//Act
const result = await manager.setup_api();
//Assert
expect(result).toEqual("Mock Login Method Called");
expect(mockLogin).toHaveBeenCalledWith("email#website.ext", "password");
});
});
Again, this is really only relevant when using ts-jest, as using babel to transform your jest typescript tests WILL support the correct hoisting behavior. This is subject to change in the future, with updates to ts-jest, but the jest.doMock() workaround seems good enough for the time being.

Unit Test library is called from wrapper library

I am building a wrapper around a javascript library in pinojs.
I'm wondering how I can write a unit test to verify the info function within pino was actually called.
Here's a code snippet
const { logger } = require(`../../../lib/index`);
describe(`when logger is configured with pino-pretty`, () => {
beforeEach(() => {
myAppLogger = logger({
prettyPrint: true
});
});
it(`then pino info method is called on pino instance`, () => {
const pinoSpy = sinon.spy(pino, 'info');
myAppLogger.info('info message');
expect(pinoSpy).to.have.been.called;
expect(pinoSpy).to.not.throw();
});
});
Where myAppLogger is just an instance of pino
pino(options, stream).child(props);

How to clear a module mock between tests in same test suite in Jest?

I've mocked some nodejs modules (one of them, for example, is fs). I have them in a __mocks__ folder (same level als node_modules) folder and the module mocking works. However, whichever "between test clearing" option I use, the next test is not "sandboxed". What is going wrong here?
A very simplified example of the mocked fs module is:
// __mocks__/fs.js
module.exports = {
existsSync: jest.fn()
.mockReturnValueOnce(1)
.mockReturnValueOnce(2)
.mockReturnValueOnce(3)
}
I'm simply expecting that in every test, whenever init() is called (see below), existsSync starts again at value 1: the first value of jest.fn().mockReturnValue(). In the testfile I have the following structure:
// init.test.js
const init = require("../init");
const { existsSync } = require("fs");
jest.mock("fs");
describe("initializes script", () => {
afterEach(() => {
// see below!
});
test("it checks for a package.json in current directory", () => {
init();
});
test("it stops script if there's a package.json in dir", () => {
init(); // should be run in clean environment!
});
}
And once again very simplified, the init.js file
const { existsSync } = require("fs");
console.log("value of mocked response : ", existsSync())
I'm getting the following results for existsSync() after the first and second run ofinit() respectively when I run in afterEach():
jest.resetModules() : 1, 2
existsSync.mockReset(): 1, undefined
existsSync.mockClear(): 1, 2
existsSync.mockRestore(): 1, undefined
Somebody know what I'am doing wrong? How do I clear module mock between tests in the same suite? I'll glady clarify if necessary. Thanks!
Reset the modules and require them again for each test:
describe("initializes script", () => {
afterEach(() => {
jest.resetModules()
});
beforeEach(() => {
jest.mock("fs");
})
test("it checks for a package.json in current directory", () => {
const init = require("../init");
init();
});
test("it stops script if there's a package.json in dir", () => {
const init = require("../init");
init();
});
}
I had problems with the solution above. I managed to solve the issue with the next snippet.
afterEach(() => {
Object.keys(mockedModule).forEach(method => mockedModule[method].mockReset())
})
I would prefer to have a native method doing this though. Something like mockedModule.mockReset().
For local variables, the scope of declaration is important.
const mockFunc1 = jest.fn() // possibly bad mock reset/clear between tests
describe('useGetMetaData', () => {
const mockFunc2 = jest.fn() // good mock reset/clear between tests
afterEach(() => {/* reset/clear mocks */})
test.todo('implement tests here')
})

Jest URL.createObjectURL is not a function

I'm developping a reactJs application. I'm using jest to test my application.
I want to test a function that download a blob.
But unfortunately I receve this error:
URL.createObjectURL is not a function
my test function:
describe('download', () => {
const documentIntial = { content: 'aaa' };
it('msSaveOrOpenBlob should not have been called when navigao is undefined', () => {
window.navigator.msSaveOrOpenBlob = null;
download(documentIntial);
expect(window.navigator.msSaveOrOpenBlob).toHaveBeenCalledTimes(0);
});
});
The function I want to test:
export const download = document => {
const blob = new Blob([base64ToArrayBuffer(document.content)], {
type: 'application/pdf',
});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob);
return;
}
const fileURL = URL.createObjectURL(blob);
window.open(fileURL);
};
This would appear to be as simple as setting up URL on the Global in Jest. Something like
describe('download', () => {
const documentIntial = { content: 'aaa' };
global.URL.createObjectURL = jest.fn();
it('msSaveOrOpenBlob should not have been called when navigao is undefined', () => {
global.URL.createObjectURL = jest.fn(() => 'details');
window.navigator.msSaveOrOpenBlob = jest.fn(() => 'details');
download(documentIntial);
expect(window.navigator.msSaveOrOpenBlob).toHaveBeenCalledTimes(1);
});
});
This should result in a test that you can also use for checking if global.URL.createObjectURL was called. As a side note: you may also run into a similar issue with window.open I would suggest mocking that as well if this becomes the case.
Since window.URL.createObjectURL is not (yet) available in jest-dom, you need to provide a mock implementation for it.
Don't forget to reset the mock implementation after each test.
describe("your test suite", () => {
window.URL.createObjectURL = jest.fn();
afterEach(() => {
window.URL.createObjectURL.mockReset();
});
it("your test case", () => {
expect(true).toBeTruthy();
});
});
jsdom, the JavaScript implementation of the WHATWG DOM used by jest doesn't implement this method yet.
You can find an open ticket about this exact issue on their github page where some workarounds are provided in comments. But if you need the blobURL to actually work you'll have to wait this FR is solved.
Workaround proposed in the comments of the issue for jest:
function noOp () { }
if (typeof window.URL.createObjectURL === 'undefined') {
Object.defineProperty(window.URL, 'createObjectURL', { value: noOp})
}
You just have to Write this in your setupTest.js
window.URL.createObjectURL = function() {};
The package jsdom-worker happens to provide this method, as well as adding support for web workers. The following worked for me:
npm install -D jsdom-worker
Then in package.json, edit or add a jest key:
{
...
"jest": {
"setupFiles": [
"jsdom-worker"
]
}
}
Just mocking the function global.URL.createObjectURL did not work for me, because the function was used by some modules during import and I got the error Jest URL.createObjectURL is not a function during import.
Instead it did help to create a file mockJsdom.js
Object.defineProperty(URL, 'createObjectURL', {
writable: true,
value: jest.fn()
})
Then import this file as the first import in your file containing the test
import './mockJsdom'
import { MyObjects} from '../../src/lib/mylib'
test('my test', () => {
// test code
}
Found here: https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom

Require not behaving as expected

I'm using the proxyquire library, which mocks packages on import.
I'm creating my own proxyquire function, which stubs a variety of packages I use regularly and want to stub regularly (meteor packages, which have a special import syntax):
// myProxyquire.js
import proxyquire from 'proxyquire';
const importsToStub = {
'meteor/meteor': { Meteor: { defer: () => {} } },
};
const myProxyquire = filePath => proxyquire(filePath, importsToStub);
export default myProxyquire;
Now I want to write a test of a file which uses one of these packages:
// src/foo.js
import { Meteor } from 'meteor/meteor'; // This import should be stubbed
export const foo = () => {
Meteor.defer(() => console.log('hi')); // This call should be stubbed
return 'bar';
};
And finally I test it like this:
// src/foo.test.js
import myProxyquire from '../myProxyquire';
// This should be looking in the `src` folder
const { foo } = myProxyquire('./foo'); // error: ENOENT: no such file
describe('foo', () => {
it("should return 'bar'", () => {
expect(foo()).to.equal('bar');
});
});
Note that my last 2 files are nested inside a subfolder src. So when I try to run this test, I get an error saying that the module ./foo couldn't be found, as it is being looked for in the "root" directory, where the myProxyquire.js file is, not the src directory as expected.
You might be able to work around that (expected) behaviour by using a module like caller-path to determine from which file myProxyquire was called, and resolving the passed path relative to that file:
'use strict'; // this line is important and should not be removed
const callerPath = require('caller-path');
const { dirname, resolve } = require('path');
module.exports.default = path => require(resolve(dirname(callerPath()), path));
However, I have no idea of this works with import (and, presumably, transpilers).

Categories

Resources