Unit Test library is called from wrapper library - javascript

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);

Related

ES6 imports and 'is not a constructor' in Jest.mock

Similar to Jest TypeError: is not a constructor in Jest.mock, except I am using ES6 imports - and the answer given to that question is not working on my situation.
Following the Jest .mock() documentation I am attempting to mock the constructor Client from the pg module.
I have a constructor, Client, imported from an ES6 module called pg. Instances of Client should have a query method.
import { Client } from "pg";
new Client({ connectionString: 'postgresql://postgres:postgres#localhost:5432/database' });
export async function doThing(client): Promise<string[]> {
var first = await client.query('wooo')
var second = await client.query('wooo')
return [first, second]
}
Here's my __tests__/test.ts
const log = console.log.bind(console)
jest.mock("pg", () => {
return {
query: jest
.fn()
.mockReturnValueOnce('one')
.mockReturnValueOnce('two'),
};
});
import { Client } from "pg";
import { doThing } from "../index";
it("works", async () => {
let client = new Client({});
var result = await doThing(client);
expect(result).toBe(['one', 'two'])
});
This is similar to the answer given in Jest TypeError: is not a constructor in Jest.mock, but it's failing here.
The code, just:
const mockDbClient = new Client({ connectionString: env.DATABASE_URL });
fails with:
TypeError: pg_1.Client is not a constructor
I note the docs mention __esModule: true is required when using default exports, but Client is not a default export from pg (I've checked).
How can I make the constructor work properly?
Some additional notes after getting an answer
Here's a slightly longer-form version of the answer, with comments about what's happening on each line - I hope people reading this find it useful!
jest.mock("pg", () => {
// Return the fake constructor function we are importing
return {
Client: jest.fn().mockImplementation(() => {
// The consturctor function returns various fake methods
return {
query: jest.fn()
.mockReturnValueOnce(firstResponse)
.mockReturnValueOnce(secondResponse),
connect: jest.fn()
}
})
}
})
When you mock the module, it needs to have the same shape as the actual module. Change:
jest.mock("pg", () => {
return {
query: jest
.fn()
.mockReturnValueOnce('one')
.mockReturnValueOnce('two'),
};
});
...to:
jest.mock("pg", () => ({
Client: jest.fn().mockImplementation(() => ({
query: jest.fn()
.mockReturnValueOnce('one')
.mockReturnValueOnce('two')
}))
}));

How to stub a libary function in JavaScript

For example, if I have main.js calling a defined in src/lib/a.js, and function a calls node-uuid.v1, how can I stub node-uuid.v1 when testing main.js?
main.js
const a = require("./src/lib/a").a
const main = () => {
return a()
}
module.exports = main
src/lib/a.js
const generateUUID = require("node-uuid").v1
const a = () => {
let temp = generateUUID()
return temp
}
module.exports = {
a
}
tests/main-test.js
const assert = require("assert")
const main = require("../main")
const sinon = require("sinon")
const uuid = require("node-uuid")
describe('main', () => {
it('should return a newly generated uuid', () => {
sinon.stub(uuid, "v1").returns("121321")
assert.equal(main(), "121321")
})
})
The sinon.stub(...) statement doesn't stub uuid.v1 for src/lib/a.js as the above test fails.
Is there a way to globally a library function so that it does the specified behavior whenever it gets called?
You should configure the stub before importing the main module. In this way the module will call the stub instead of the original function.
const assert = require("assert")
const sinon = require("sinon")
const uuid = require("node-uuid")
describe('main', () => {
it('should return a newly generated uuid', () => {
sinon.stub(uuid, "v1").returns("121321")
const main = require("../main")
assert.equal(main(), "121321")
})
})
Bear in mind that node-uuid is deprecated as you can see by this warning
[Deprecation warning: The use of require('uuid') is deprecated and
will not be supported after version 3.x of this module. Instead, use
require('uuid/[v1|v3|v4|v5]') as shown in the examples below.]
About how to stub that for testing would be a bit more harder than before as actually there is no an easy way to mock a standalone function using sinon
Creating a custom module
//custom uuid
module.exports.v1 = require('uuid/v1');
Requiring uuid from the custom module in your project
const uuid = require('<path_to_custom_module>');
Sinon.stub(uuid, 'v1').returns('12345');

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')
})

Mock a dependency's constructor Jest

I'm a newbie to Jest. I've managed to mock my own stuff, but seem to be stuck mocking a module. Specifically constructors.
usage.js
const AWS = require("aws-sdk")
cw = new AWS.CloudWatch({apiVersion: "2010-08-01"})
...
function myMetrics(params) {
cw.putMetricData(params, function(err, data){})
}
I'd like to do something like this in the tests.
const AWS = jest.mock("aws-sdk")
class FakeMetrics {
constructor() {}
putMetricData(foo,callback) {
callback(null, "yay!")
}
}
AWS.CloudWatch = jest.fn( (props) => new FakeMetrics())
However when I come to use it in usage.js the cw is a mockConstructor not a FakeMetrics
I realise that my approach might be 'less than idiomatic' so I'd be greatful for any pointers.
This is a minimal example https://github.com/ollyjshaw/jest_constructor_so
npm install -g jest
jest
Above answer works. However, after some time working with jest I would just use the mockImplementation functionality which is useful for mocking constructors.
Below code could be an example:
import * as AWS from 'aws-sdk';
jest.mock('aws-sdk', ()=> {
return {
CloudWatch : jest.fn().mockImplementation(() => { return {} })
}
});
test('AWS.CloudWatch is called', () => {
new AWS.CloudWatch();
expect(AWS.CloudWatch).toHaveBeenCalledTimes(1);
});
Note that in the example the new CloudWatch() just returns an empty object.
The problem is how a module is being mocked. As the reference states,
Mocks a module with an auto-mocked version when it is being required.
<...>
Returns the jest object for chaining.
AWS is not module object but jest object, and assigning AWS.CloudFormation will affect nothing.
Also, it's CloudWatch in one place and CloudFormation in another.
Testing framework doesn't require to reinvent mock functions, they are already there. It should be something like:
const AWS = require("aws-sdk");
const fakePutMetricData = jest.fn()
const FakeCloudWatch = jest.fn(() => ({
putMetricData: fakePutMetricData
}));
AWS.CloudWatch = FakeCloudWatch;
And asserted like:
expect(fakePutMetricData).toHaveBeenCalledTimes(1);
According to the documentation mockImplementation can also be used to mock class constructors:
// SomeClass.js
module.exports = class SomeClass {
method(a, b) {}
};
// OtherModule.test.js
jest.mock('./SomeClass'); // this happens automatically with automocking
const SomeClass = require('./SomeClass');
const mockMethod= jest.fn();
SomeClass.mockImplementation(() => {
return {
method: mockMethod,
};
});
const some = new SomeClass();
some.method('a', 'b');
console.log('Calls to method: ', mockMethod.mock.calls);
If your class constructor has parameters, you could pass jest.fn() as an argument (eg. const some = new SomeClass(jest.fn(), jest.fn());

Mock a method of a service called by the tested one when using Jest

I am trying to mock a method's service i export as a module from my test.
This is something i use to do with "sinon", but i would like to use jest as much as possible.
This is a classic test, i have an "authentication" service and a "mailer" service.
The "authentication" service can register new users, and after each new registration, it ask the mailer service to send the new user a "welcome email".
So testing the register method of my authentication service, i would like to assert (and mock) the "send" method of the mailer service.
How to do that? Here is what i tried, but it calls the original mailer.send method:
// authentication.js
const mailer = require('./mailer');
class authentication {
register() { // The method i am trying to test
// ...
mailer.send();
}
}
const authentication = new Authentication();
module.exports = authentication;
// mailer.js
class Mailer {
send() { // The method i am trying to mock
// ...
}
}
const mailer = new Mailer();
module.exports = mailer;
// authentication.test.js
const authentication = require('../../services/authentication');
describe('Service Authentication', () => {
describe('register', () => {
test('should send a welcome email', done => {
co(function* () {
try {
jest.mock('../../services/mailer');
const mailer = require('../../services/mailer');
mailer.send = jest.fn( () => { // I would like this mock to be called in authentication.register()
console.log('SEND MOCK CALLED !');
return Promise.resolve();
});
yield authentication.register(knownUser);
// expect();
done();
} catch(e) {
done(e);
}
});
});
});
});
First you have to mock the mailer module with a spy so you can later set. And you to let jest know about using a promise in your test, have a look at the docs for the two ways to do this.
const authentication = require('../../services/authentication');
const mailer = require('../../services/mailer');
jest.mock('../../services/mailer', () => ({send: jest.fn()}));
describe('Service Authentication', () => {
describe('register', () => {
test('should send a welcome email', async() => {
const p = Promise.resolve()
mailer.send.mockImplementation(() => p)
authentication.register(knownUser);
await p
expect(mailer.send).toHaveBeenCalled;
}
});
});
});
});

Categories

Resources