How to unit test node-cron job - javascript

I need to call a function using node-cron and want to write a unit test case for that. the unit test case should be able to test if the function is getting calling based on the pattern.
Below is my code
const server = (module.exports = {
cronJob: null,
scheduledJob: function(pattern) {
server.cronJob = cron.schedule(pattern, () => {
server.run();
});
},
run: function() {
console.log("run called");
},
});
describe("entry point test suite", () => {
it("should call function every second", (done) => {
const pattern = "* * * * * *";
let spy = sinon.spy(server, "run");
server.scheduledJob(pattern);
server.cronJob.Start();
// to do wait for 3 sencond
server.cronJob.Stop();
expect(spy.callCount).eq(3);
});
});
Two questions:
other than setTimeout what option I have to wait for 3 seconds so that cron job will run 3 times as pattern is for each second.
This test is failing with error server.cronjob.start is not a function.
How can I make this work?

Here is the unit testing solution:
server.js:
const cron = require("node-cron");
const server = (module.exports = {
cronJob: null,
scheduledJob: function(pattern) {
server.cronJob = cron.schedule(pattern, () => {
server.run();
});
},
run: function() {
console.log("run called");
},
});
server.test.js:
const server = require("./server");
const sinon = require("sinon");
const cron = require("node-cron");
const { expect } = require("chai");
describe("57208090", () => {
afterEach(() => {
sinon.restore();
});
describe("#scheduledJob", () => {
it("should schedule job", () => {
const pattern = "* * * * * *";
const runStub = sinon.stub(server, "run");
const scheduleStub = sinon
.stub(cron, "schedule")
.yields()
.returns({});
server.scheduledJob(pattern);
sinon.assert.calledWith(scheduleStub, pattern, sinon.match.func);
sinon.assert.calledOnce(runStub);
expect(server.cronJob).to.be.eql({});
});
});
describe("#run", () => {
it("should run server", () => {
const logSpy = sinon.spy(console, "log");
server.run();
sinon.assert.calledWith(logSpy, "run called");
});
});
});
Unit test result with 100% coverage:
57208090
#scheduledJob
✓ should schedule job
#run
run called
✓ should run server
2 passing (12ms)
----------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
server.js | 100 | 100 | 100 | 100 | |
server.test.js | 100 | 100 | 100 | 100 | |
----------------|----------|----------|----------|----------|-------------------|
You asked for unit testing. If you need an integration testing, please create a new post.
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57208090

Related

Issues using Sinon to stub out Pino

I am attempting to write unit test for a service function that returns a Pino log message when ran. I have built a stub, using Sinon, from the logger module I am using in service.js, but have not been able to get a successful test. The test returns: AssertionError: expected error to have been called exactly once, but it was called 0 times
Ideally I would like to be able to assert that the logger was called, and that function returned with the exact logger call and message.
Below is some sample code for what I am trying to achieve
logger.js
const pino = require('pino');
const defaultLogger = pino({}, 'output.log');
module.exports = {
defaultLogger
}
service.js
const path = require('path');
const { defaultLogger } = require('../common/logger');
const logger = defaultLogger.child({ filename: path.basename(__filename) });
const logResponse = () => {
return logger.info('successful');
};
service.test.js
const sinon = require('sinon');
const chai = require('chai');
const sinonChai = require('sinon-chai');
const service = require('../service.js')
const { defaultLogger } = require('../common/logger');
const { expect } = chai;
chai.should();
chai.use(sinonChai);
describe('Service Test', () => {
it('should return a log message', () => {
const spy = sinon.spy(service, 'logResponse')
const stub = sinon.stub(defaultLogger, 'error');
spy.should.have.been.calledOnce;
expect(stub).to.have.been.calledOnce;
spy.should.have.returned(logger.info('successful'));
})
})
Here is the unit test solution:
./logger.js:
const pino = require('pino');
const defaultLogger = pino({}, 'output.log');
module.exports = {
defaultLogger,
};
./service.js:
const path = require('path');
const { defaultLogger } = require('./logger');
const logger = defaultLogger.child({ filename: path.basename(__filename) });
const logResponse = () => {
return logger.info('successful');
};
module.exports = {
logResponse,
};
./service.test.js:
const { defaultLogger } = require('./logger');
const sinon = require('sinon');
const chai = require('chai');
const { expect } = chai;
describe('63618186', () => {
it('should return a log message ', () => {
const loggerStub = {
info: sinon.stub().returns('anything'),
};
sinon.stub(defaultLogger, 'child').returns(loggerStub);
const service = require('./service');
const actual = service.logResponse();
expect(actual).to.be.equal('anything');
sinon.assert.calledOnce(defaultLogger.child);
sinon.assert.calledWithExactly(loggerStub.info, 'successful');
});
});
unit test result with coverage report:
63618186
✓ should return a log message
1 passing (41ms)
------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
logger.js | 100 | 100 | 100 | 100 |
service.js | 100 | 100 | 100 | 100 |
------------|---------|----------|---------|---------|-------------------

write a unit case for event.preventDefault using jest

I am new to jest, i need a help for writing unit case for event.preventDefault using jest in react,
below are the my code,
export const removeValuesFromTextAreaEvent = ({ removeValuesFromTextArea }) => (
event,
rows
) => {
event.preventDefault();
removeValuesFromTextArea({ rowID: rows });
};
I am getting
TypeError: Cannot read property 'preventDefault' of undefined.
The test
describe("removeValuesFromTextAreaEvent", () => {
it("returns a function that calls removeValuesFromTextAreaEvent with rows", () => {
const removeValuesFromTextArea = jest.fn();
const rowID = 1;
const event = { preventDefault: jest.fn() };
removeValuesFromTextAreaEvent({ removeValuesFromTextArea })(event);
expect(event.preventDefault).toHaveBeenCalled();
removeValuesFromTextAreaEvent({ rowID, removeValuesFromTextArea })();
expect(removeValuesFromTextArea).toHaveBeenCalledWith({ rowID });
});
});
Here is the unit test solution:
index.js:
export const removeValuesFromTextAreaEvent = ({ removeValuesFromTextArea }) => (event, rows) => {
event.preventDefault();
removeValuesFromTextArea({ rowID: rows });
};
index.test.js:
import { removeValuesFromTextAreaEvent } from './';
describe('removeValuesFromTextAreaEvent', () => {
it('returns a function that calls removeValuesFromTextAreaEvent with rows', () => {
const removeValuesFromTextArea = jest.fn();
const rowID = 1;
const event = { preventDefault: jest.fn() };
removeValuesFromTextAreaEvent({ removeValuesFromTextArea })(event, rowID);
expect(event.preventDefault).toHaveBeenCalled();
expect(removeValuesFromTextArea).toHaveBeenCalledWith({ rowID });
});
});
unit test results with 100% coverage:
PASS stackoverflow/61014741/index.test.js (8.616s)
removeValuesFromTextAreaEvent
✓ returns a function that calls removeValuesFromTextAreaEvent with rows (3ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.24s

jest.mock - how to check that function inside function has been called

This is a part of my app:
import validationSchema from "./../_validation/report";
const reportModel = require("../models/report");
ctrl.addReport = async (req, res) => {
const { body } = req;
try {
const validatedData = await validationSchema.validate(body);
const report = await reportModel(req.dbConnection).addReport(validatedData);
// something more
} catch (err) {
throw boom.badRequest(err);
}
};
module.exports = ctrl;
I would like to write some unit test but I want to test that addReport from reportModel has been called with the correct argument.
To mock reportModel I use jest.mock like this:
const reportModel = require("../models/report");
jest.mock('../models/report', () => {
return () => {
return {
addReport: jest.fn(() => {
return true
})
}
}
});
// do some tests and call function which call addReport from reportModel
expect(reportModel().addReport).toHaveBeenCalledTimes(1);
I've got 0. How can I check that addReport from reportModel has been called?
You didn't mock ./models/report module correctly. Here is the solution:
ctrl.js:
import validationSchema from './_validation/report';
import reportModel from './models/report';
const ctrl = {};
ctrl.addReport = async (req, res) => {
const { body } = req;
const validatedData = await validationSchema.validate(body);
const report = await reportModel(req.dbConnection).addReport(validatedData);
};
module.exports = ctrl;
./models/report.js:
function reportModel(connection) {
return {
async addReport(data) {
console.log('addReport');
},
};
}
export default reportModel;
./_validation/report.js:
const validationSchema = {
validate(body) {
return body;
},
};
export default validationSchema;
ctrl.test.js:
import reportModel from './models/report';
const ctrl = require('./ctrl');
jest.mock('./models/report', () => {
const mReportModel = {
addReport: jest.fn(() => true),
};
return jest.fn(() => mReportModel);
});
describe('59431651', () => {
it('should pass', async () => {
const mReq = { body: 'mocked data', dbConnection: {} };
const mRes = {};
await ctrl.addReport(mReq, mRes);
expect(reportModel).toBeCalledWith(mReq.dbConnection);
expect(reportModel(mReq.dbConnection).addReport).toHaveBeenCalledTimes(1);
});
});
Unit test result with coverage report:
PASS src/stackoverflow/59431651/ctrl.test.js
59431651
✓ should pass (7ms)
----------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
59431651 | 100 | 100 | 100 | 100 | |
ctrl.js | 100 | 100 | 100 | 100 | |
59431651/_validation | 100 | 100 | 100 | 100 | |
report.js | 100 | 100 | 100 | 100 | |
----------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.682s, estimated 11s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59431651

Jest mock function's inner variable and change function's behavior?

i have little experience with jest as i am trying to change variable in my function as we expect to have error thrown if the function's inner variable(baseUrl) changed to null, my function :
buildUrl.js:
export function buildUrl(contentId, data, options = {}) {
let baseUrl = config.has('imgBaseUrl') && config.get('imgBaseUrl');
if (!baseUrl) {
throw new Error('some error');
}
}
i need to mock the baseUrl to value of null for example and test it
buildUrl.test.js
import {buildUrl} from "./buildURL";
....
it('throw an error when "baseUrl" is not configured', () => {
let mockBaseUrl = {baseUrl: null};
jest.mock('./buildURL', ()=> mockBaseUrl);
// jest.mock('../../../config/test', ()=>mockImgBaseUrl); // or mock the config to be used by the function?
expect(()=> buildUrl('1.44444', data[0], defaultOptions)).toThrow(
'some error'
);
});
another approach using jest.fn() didnt work as expected , maybe i am missing something here...
Here is the unit test solution:
baseUrl.js:
import config from './config';
export function buildUrl(contentId, data, options = {}) {
let baseUrl = config.has('imgBaseUrl') && config.get('imgBaseUrl');
if (!baseUrl) {
throw new Error('some error');
}
console.log(baseUrl);
}
config.js:
export default {
config: {},
has(key) {
return !!config[key];
},
get(key) {
return config[key];
}
};
baseUrl.spec.js:
import { buildUrl } from './buildUrl';
import config from './config';
describe('buildUrl', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should throw error when baseUrl is null', () => {
const defaultOptions = {};
const data = ['fake data'];
const hasSpy = jest.spyOn(config, 'has').mockReturnValueOnce(true);
const getSpy = jest.spyOn(config, 'get').mockReturnValueOnce(null);
expect(() => buildUrl('1.44444', data[0], defaultOptions)).toThrowError('some error');
expect(hasSpy).toBeCalledWith('imgBaseUrl');
expect(getSpy).toBeCalledWith('imgBaseUrl');
});
it('should log baseUrl', () => {
const defaultOptions = {};
const data = ['fake data'];
const hasSpy = jest.spyOn(config, 'has').mockReturnValueOnce(true);
const getSpy = jest.spyOn(config, 'get').mockReturnValueOnce('https://github.com/mrdulin');
const logSpy = jest.spyOn(console, 'log');
buildUrl('1.44444', data[0], defaultOptions);
expect(hasSpy).toBeCalledWith('imgBaseUrl');
expect(getSpy).toBeCalledWith('imgBaseUrl');
expect(logSpy).toBeCalledWith('https://github.com/mrdulin');
});
});
Unit test result:
PASS src/stackoverflow/48006588/buildUrl.spec.js (8.595s)
buildUrl
✓ should throw error when baseUrl is null (9ms)
✓ should log baseUrl (7ms)
console.log node_modules/jest-mock/build/index.js:860
https://github.com/mrdulin
-------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files | 80 | 83.33 | 33.33 | 77.78 | |
buildUrl.js | 100 | 83.33 | 100 | 100 | 3 |
config.js | 33.33 | 100 | 0 | 33.33 | 4,7 |
-------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 9.768s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/48006588
I think you can do this:
jest.mock('./buildURL', () => {buildUrl: jest.fn()})
buildUrl.mockImplementation(() => {baseUrl: null})
See Jest docs

unit test for web socket in javascript

I need to write unit test using sinon to web socket client.
the code is as following:
Socket = {
connect: function ()
{
socket = new WebSocket('ws://localhost:12345');
socket.onopen = function()
{
console.log('connected to the server');
};
socket.onmessage = function(message)
{
console.log('Received:', message.data);
};
}
};
We need return the socket instance at last in the connect method. Because you assigned two new functions to onopen and onmessage events. It will override the spy or stub methods on the socket object.
Test environment: Node
Here is the unit test solution:
index.js:
const Socket = {
connect: function() {
socket = new WebSocket("ws://localhost:12345");
socket.onopen = function() {
console.log("connected to the server");
};
socket.onmessage = function(message) {
console.log("Received:", message.data);
};
return socket;
}
};
module.exports = Socket;
index.spec.js:
const sinon = require("sinon");
const { expect } = require("chai");
const Socket = require("./index");
class WebSocket {
constructor(uri) {}
onopen() {}
onmessage() {}
}
global.WebSocket = WebSocket;
describe("17806481", () => {
it("should test connect correctly", () => {
const logSpy = sinon.spy(console, "log");
const socket = Socket.connect();
const onopenSpy = sinon.spy(socket, "onopen");
const onmessageSpy = sinon.spy(socket, "onmessage");
onopenSpy();
expect(logSpy.firstCall.calledWith("connected to the server")).to.be.true;
const mMessage = { data: "fake data" };
onmessageSpy(mMessage);
expect(logSpy.secondCall.calledWith("Received:", mMessage.data)).to.be.true;
});
});
Unit test result with 100% coverage for Socket module:
17806481
connected to the server
Received: fake data
✓ should test connect correctly
1 passing (10ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 75 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
index.spec.js | 100 | 100 | 60 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/17806481

Categories