Writing a test to verify object properties in jest(NodeJs) - javascript

function.js
function sesSendEmail(message) {
var ses = new aws.SES({ apiVersion: '2020-12-01' });
var params = {
Source: 'xyz#gmail.com',
Template: 'deviceUsageStatisticsEmailTemplate',
Destination: {
ToAddresses: ['abc#gmail.com'],
},
TemplateData: message,
};
ses.sendTemplatedEmail(params, (err, data) => {
if (err) console.error;
// an error occurred
else console.log(data); // successful response
});
}
const exportFunctions = {
sesSendEmail: sesSendEmail,
};
module.exports = exportFunctions;
I want to write a test to verify params(Source, template..etc) so I was trying to mock sendTemplatedEmail.
Function.test.js
describe('sesSendEmail', () => {
const mocksendTemplatedEmail = {
sendTemplatedEmail: jest.fn()
}
index.sesSendEmail(mocksendTemplatedEmail);
test('Check if Source is correct', () => {
console.log(mocksendTemplatedEmail.sendTemplatedEmail.mock)
})
})
However, console.log is empty. Please advise.

Here is the unit test solution:
index.js:
const aws = require('aws-sdk');
function sesSendEmail(message) {
const ses = new aws.SES({ apiVersion: '2020-12-01' });
const params = {
Source: 'xyz#gmail.com',
Template: 'deviceUsageStatisticsEmailTemplate',
Destination: {
ToAddresses: ['abc#gmail.com'],
},
TemplateData: message,
};
ses.sendTemplatedEmail(params, (err, data) => {
if (err) {
return console.error(err);
}
console.log(data);
});
}
const exportFunctions = { sesSendEmail };
module.exports = exportFunctions;
index.test.js:
const index = require('.');
const aws = require('aws-sdk');
jest.mock('aws-sdk', () => {
const mSes = {
sendTemplatedEmail: jest.fn(),
};
return { SES: jest.fn(() => mSes) };
});
describe('59877312', () => {
let ses;
beforeEach(() => {
ses = new aws.SES();
});
afterEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});
describe('sesSendEmail', () => {
it('should send templated email success', () => {
jest.spyOn(console, 'log');
const mData = {};
ses.sendTemplatedEmail.mockImplementationOnce((params, callback) => {
callback(null, mData);
});
const message = 'mock message';
index.sesSendEmail(message);
expect(aws.SES).toBeCalledWith({ apiVersion: '2020-12-01' });
expect(ses.sendTemplatedEmail).toBeCalledWith(
{
Source: 'xyz#gmail.com',
Template: 'deviceUsageStatisticsEmailTemplate',
Destination: {
ToAddresses: ['abc#gmail.com'],
},
TemplateData: message,
},
expect.any(Function),
);
expect(console.log).toBeCalledWith(mData);
});
it('should handle error', () => {
jest.spyOn(console, 'error');
const mError = new Error('network error');
ses.sendTemplatedEmail.mockImplementationOnce((params, callback) => {
callback(mError, null);
});
const message = 'mock message';
index.sesSendEmail(message);
expect(aws.SES).toBeCalledWith({ apiVersion: '2020-12-01' });
expect(ses.sendTemplatedEmail).toBeCalledWith(
{
Source: 'xyz#gmail.com',
Template: 'deviceUsageStatisticsEmailTemplate',
Destination: {
ToAddresses: ['abc#gmail.com'],
},
TemplateData: message,
},
expect.any(Function),
);
expect(console.error).toBeCalledWith(mError);
});
});
});
Unit test results with 100% coverage:
PASS src/stackoverflow/59877312/index.test.js (11.103s)
59877312
sesSendEmail
✓ should send templated email success (16ms)
✓ should handle error (3ms)
console.log node_modules/jest-mock/build/index.js:860
{}
console.error node_modules/jest-mock/build/index.js:860
Error: network error
at Object.it (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/59877312/index.test.js:46:22)
at Object.asyncJestTest (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:102:37)
at resolve (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:43:12)
at new Promise (<anonymous>)
at mapper (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
at promise.then (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:73:41)
at process._tickCallback (internal/process/next_tick.js:68:7)
----------|----------|----------|----------|----------|-------------------|
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: 2 passed, 2 total
Snapshots: 0 total
Time: 12.485s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59877312

Related

is there a way to mock the the Promise.resolve in a function

So I tried to mock a jwt.verify function. below is the function itself and then the mock.
try {
const decodedJwt = new Promise((resolve, reject) => {
jwt.verify(
token,
getPublicKey,
{
algorithms: ['RS256'],
ignoreExpiration: false,
},
(decodeError, decodedValue) => {
if (decodeError) {
reject(decodeError);
}
resolve(decodedValue);
}
);
});
return await decodedJwt;
} catch (error) {
logger.error(error);
return null;
}
The Mock for the verify part
export const jwtVerifyMock = jest.fn();
jest.mock('jsonwebtoken', () => {
return {
decode: jwtDecodeMock,
verify: jwtVerifyMock,
};
});
then this is how I use it in my test
it('decodeJWT should should verify token', async () => {
jwtVerifyMock.mockImplementation(async () => Promise.resolve({ exp: config.exp }));
return decodeJwt(config.jwtToken, true).then(async (value) => {
console.log('payload2', value);
const payload = value as Record<string, unknown>;
expect(payload.exp).toEqual(config.exp);
});
});
But for some reason, it doesn't get resolved. and I get a
Async callback was not invoked within the 60000 ms timeout Error
I tried using mockReturn value but that doesn't work as well. So the next thing I'm guessing is that the resolve function that was passed as a callback to the jwt.verify is where my problem lie.
You should mock the implementation of jwt.verify() and execute the callback function manually with different arguments.
E.g.
decode.ts:
import jwt from 'jsonwebtoken';
export async function decode(token, getPublicKey) {
try {
const decodedJwt = new Promise((resolve, reject) => {
jwt.verify(
token,
getPublicKey,
{
algorithms: ['RS256'],
ignoreExpiration: false,
},
(decodeError, decodedValue) => {
if (decodeError) {
reject(decodeError);
}
resolve(decodedValue);
}
);
});
return await decodedJwt;
} catch (error) {
console.error(error);
return null;
}
}
decode.test.ts:
import { decode } from './decode';
import jwt, { JsonWebTokenError } from 'jsonwebtoken';
describe('66966317', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should decode value', async () => {
const decodedvalue = { name: 'teresa teng' };
const verifySpy = jest.spyOn(jwt, 'verify').mockImplementationOnce((token, getPublicKey, options, callback) => {
callback!(null, decodedvalue);
});
const actual = await decode('teresa teng', true);
expect(actual).toEqual({ name: 'teresa teng' });
expect(verifySpy).toBeCalledWith(
'teresa teng',
true as any,
{ algorithms: ['RS256'], ignoreExpiration: false },
expect.any(Function)
);
});
it('should handle decode error', async () => {
const decodedError = new JsonWebTokenError('network');
const verifySpy = jest.spyOn(jwt, 'verify').mockImplementationOnce((token, getPublicKey, options, callback) => {
callback!(decodedError, undefined);
});
const actual = await decode('teresa teng', true);
expect(actual).toBeNull();
expect(verifySpy).toBeCalledWith(
'teresa teng',
true as any,
{ algorithms: ['RS256'], ignoreExpiration: false },
expect.any(Function)
);
});
});
unit test result:
PASS examples/66966317/decode.test.ts (7.701 s)
66966317
✓ should decode value (3 ms)
✓ should handle decode error (17 ms)
console.error
JsonWebTokenError { name: 'JsonWebTokenError', message: 'network' }
23 | return await decodedJwt;
24 | } catch (error) {
> 25 | console.error(error);
| ^
26 | return null;
27 | }
28 | }
at Object.<anonymous> (examples/66966317/decode.ts:25:13)
at Generator.throw (<anonymous>)
at rejected (examples/66966317/decode.ts:1046:32)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
decode.ts | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 8.749 s

Testing client-side SSE with Jest and ES modules

The objective is to put the EventSource-related functionality in a class such as:
export default class EventSourceSetup {
constructor() {
let eventSource = new EventSource('http://localhost');
eventSource.addEventListener('loading', function (event) {
})
eventSource.addEventListener('loaded', function (event) {
})
eventSource.addEventListener('error', function (event) {
})
eventSource.onerror = error => {
console.error('EventSource failed: ', error);
};
}
}
The server should be mocked and the complete client-side functionality with window and EventSource in the browser should be used.
And to test it such as:
import EventSourceSetup from './thumbnails'
describe('SSE', () => {
beforeAll(() => {
});
it('first', () => {
const eventSourceSetup = new EventSourceSetup();
});
});
But when I do this I see the following error:
ReferenceError: EventSource is not defined
at new EventSourceSetup (/Users/pharmosan/IdeaProjects/thumbnails-frontend/thumbnails.js:3:27)
at Object.<anonymous> (/Users/pharmosan/IdeaProjects/thumbnails-frontend/thumbnails.test.js:8:34)
at Object.asyncJestTest (/Users/pharmosan/IdeaProjects/thumbnails-frontend/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:100:37)
at /Users/pharmosan/IdeaProjects/thumbnails-frontend/node_modules/jest-jasmine2/build/queueRunner.js:43:12
at new Promise (<anonymous>)
at mapper (/Users/pharmosan/IdeaProjects/thumbnails-frontend/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
at /Users/pharmosan/IdeaProjects/thumbnails-frontend/node_modules/jest-jasmine2/build/queueRunner.js:73:41
at processTicksAndRejections (internal/process/task_queues.js:97:5)
Here is the unit test solution:
index.js:
export default class EventSourceSetup {
eventSource;
constructor() {
let eventSource = new EventSource('http://localhost');
this.eventSource = eventSource;
eventSource.addEventListener('loading', function(event) {
console.log('loading');
});
eventSource.addEventListener('loaded', function(event) {
console.log('loaded');
});
eventSource.addEventListener('error', function(event) {
console.log('error');
});
eventSource.onerror = (error) => {
console.error('EventSource failed: ', error);
};
}
}
index.test.js:
import EventSourceSetup from '.';
const mEventSourceInstance = {
addEventListener: jest.fn(),
};
const mEventSource = jest.fn(() => mEventSourceInstance);
global.EventSource = mEventSource;
describe('SSE', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('first', () => {
mEventSourceInstance.addEventListener.mockImplementation((event, handler) => {
if (event === 'loading' || event === 'loaded') {
handler();
}
});
const logSpy = jest.spyOn(console, 'log');
new EventSourceSetup();
expect(mEventSource).toBeCalledWith('http://localhost');
expect(mEventSourceInstance.addEventListener).toBeCalledTimes(3);
expect(logSpy).toBeCalledWith('loading');
expect(logSpy).toBeCalledWith('loaded');
});
it('should handle error', () => {
mEventSourceInstance.addEventListener.mockImplementation((event, handler) => {
if (event === 'error') {
handler();
}
});
const logSpy = jest.spyOn(console, 'log');
new EventSourceSetup();
expect(mEventSource).toBeCalledWith('http://localhost');
expect(mEventSourceInstance.addEventListener).toBeCalledTimes(3);
expect(logSpy).toBeCalledWith('error');
});
it('should handle onerror', () => {
const eventSourceSetup = new EventSourceSetup();
const errorLogSpy = jest.spyOn(console, 'error');
const mError = new Error('network');
eventSourceSetup.eventSource.onerror(mError);
expect(errorLogSpy).toBeCalledWith('EventSource failed: ', mError);
});
});
Unit test results with 100% coverage:
PASS stackoverflow/60409694/index.test.js (9.572s)
SSE
✓ first (31ms)
✓ should handle error (1ms)
✓ should handle onerror (19ms)
console.log node_modules/jest-mock/build/index.js:814
loading
console.log node_modules/jest-mock/build/index.js:814
loaded
console.log node_modules/jest-mock/build/index.js:814
error
console.log node_modules/jest-mock/build/index.js:814
error
console.error node_modules/jest-mock/build/index.js:814
EventSource failed: Error: network
at Object.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/stackoverflow/60409694/index.test.js:44:20)
at Object.asyncJestTest (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:100:37)
at resolve (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:43:12)
at new Promise (<anonymous>)
at mapper (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
at promise.then (/Users/ldu020/workspace/github.com/mrdulin/react-apollo-graphql-starter-kit/node_modules/jest-jasmine2/build/queueRunner.js:73:41)
at process._tickCallback (internal/process/next_tick.js:68:7)
----------|---------|----------|---------|---------|-------------------
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: 3 passed, 3 total
Snapshots: 0 total
Time: 12.222s
jest.config.js:
module.exports = {
preset: 'ts-jest/presets/js-with-ts',
testMatch: ['**/?(*.)+(spec|test).[jt]s?(x)'],
verbose: true,
};

TypeError: sns.publish is not a function , jest mock AWS SNS

I am trying to mock AWS.SNS and I am getting error. I referred posts on StackOverflow and could come up with below. Still, I am getting an error. I have omitted the irrelevant portion. Can someone please help me?
Below is my index.ts
import { SNS } from "aws-sdk";
export const thishandler = async (event: thisSNSEvent): Promise<any> => {
// I have omitted other code that works and not related to issue I am facing.
// I am receiving correct value of 'snsMessagetoBeSent' I verified that.
const response = await sendThisToSNS(snsMessagetoBeSent);
} // thishandler ends here
async function sendThisToSNS(thisMessage: snsAWSMessage) {
const sns = new SNS();
const TOPIC_ARN = process.env.THIS_TOPIC_ARN;
var params = {
Message: JSON.stringify(thisMessage), /* required */
TopicArn: TOPIC_ARN
};
return await sns.publish(params).promise();
}
My test case is below
jest.mock('aws-sdk', () => {
const mockedSNS = {
publish: jest.fn().mockReturnThis(),
promise: jest.fn()
};
return {
SNS: jest.fn(() => mockedSNS),
};
});
import aws, { SNS } from 'aws-sdk';
const snsPublishPromise = new aws.SNS().publish().promise;
import { thishandler } from "../src/index";
describe("async testing", () => {
beforeEach(() => {
jest.restoreAllMocks();
jest.resetAllMocks();
});
it("async test", async () => {
const ENRICHER_SNS_TOPIC_ARN = process.env.ENRICHER_SNS_TOPIC_ARN;
process.env.ENRICHER_SNS_TOPIC_ARN = "OUR-SNS-TOPIC";
const mockedResponseData ={
"Success": "OK"
};
(snsPublishPromise as any).mockResolvedValueOnce(mockedResponseData);
const result = await thishandler(thisSNSEvent);
});
I get error as TypeError: sns.publish is not a function
Here is the unit test solution:
index.ts:
import { SNS } from 'aws-sdk';
export const thishandler = async (event): Promise<any> => {
const snsMessagetoBeSent = {};
const response = await sendThisToSNS(snsMessagetoBeSent);
return response;
};
async function sendThisToSNS(thisMessage) {
const sns = new SNS();
const TOPIC_ARN = process.env.THIS_TOPIC_ARN;
const params = {
Message: JSON.stringify(thisMessage),
TopicArn: TOPIC_ARN,
};
return await sns.publish(params).promise();
}
index.test.ts:
import { thishandler } from './';
import { SNS } from 'aws-sdk';
jest.mock('aws-sdk', () => {
const mSNS = {
publish: jest.fn().mockReturnThis(),
promise: jest.fn(),
};
return { SNS: jest.fn(() => mSNS) };
});
describe('59810802', () => {
let sns;
beforeEach(() => {
sns = new SNS();
});
afterEach(() => {
jest.clearAllMocks();
});
it('should pass', async () => {
const THIS_TOPIC_ARN = process.env.THIS_TOPIC_ARN;
process.env.THIS_TOPIC_ARN = 'OUR-SNS-TOPIC';
const mockedResponseData = {
Success: 'OK',
};
sns.publish().promise.mockResolvedValueOnce(mockedResponseData);
const mEvent = {};
const actual = await thishandler(mEvent);
expect(actual).toEqual(mockedResponseData);
expect(sns.publish).toBeCalledWith({ Message: JSON.stringify({}), TopicArn: 'OUR-SNS-TOPIC' });
expect(sns.publish().promise).toBeCalledTimes(1);
process.env.THIS_TOPIC_ARN = THIS_TOPIC_ARN;
});
});
Unit test results with 100% coverage:
PASS src/stackoverflow/59810802/index.test.ts (13.435s)
59810802
✓ should pass (9ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 15.446s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59810802

How to mock a service in Jest with JavaScript?

My code looks like this
const { MyClient } = require('some-service')
const invokeMe = async (input1, input2) => {
const client = new MyClient({
name: 'my-name'
})
return await client.invoke({
input1,
input2
}).catch((err) => {
throw err
})
}
This is what I have, how do I properly mock this service and spy on what it's called with?
const { MyClient } = require('some-service')
describe('test my client', () => {
it('invoke my client', () => {
const response = {
data: []
}
expect(invokeMe('abc', '123')).resolves.toEqual(response)
expect(MyClient).toBeCalledWith({
input1: 'abc',
input2: '123'
})
})
})
Edit: Why does the below still call the original function?
it('invoke my client', () => {
const mockInvoke = jest.fn().mockImplementation(() => Promise.resolve({
data: []
}))
const mockMyClient = () => {
return { invoke: mockInvoke }
}
const mockSomeService = {
MyClient: mockMyClient
}
jest.doMock('some-service', () => mockSomeService
...
})
You can use jest.mock(moduleName, factory, options) mock the imported service
E.g.
index.js:
const { MyClient } = require('./some-service');
const invokeMe = async (input1, input2) => {
const client = new MyClient({
name: 'my-name',
});
return await client
.invoke({
input1,
input2,
})
.catch((err) => {
throw err;
});
};
module.exports = invokeMe;
some-service.js:
class MyClient {
async invoke(input1, input2) {
return 'real response';
}
}
module.exports = { MyClient };
index.test.js:
const invokeMe = require('./');
const { MyClient } = require('./some-service');
jest.mock('./some-service', () => {
const mMyClient = { invoke: jest.fn() };
return { MyClient: jest.fn(() => mMyClient) };
});
describe('60008679', () => {
it('should invoke', async () => {
const client = new MyClient();
client.invoke.mockResolvedValueOnce('fake response');
const actual = await invokeMe('a', 'b');
expect(actual).toBe('fake response');
expect(MyClient).toBeCalledWith({ name: 'my-name' });
expect(client.invoke).toBeCalledWith({ input1: 'a', input2: 'b' });
});
it('should handle error', async () => {
const client = new MyClient();
const mError = new Error('some error');
client.invoke.mockRejectedValueOnce(mError);
await expect(invokeMe('a', 'b')).rejects.toThrowError(mError);
expect(MyClient).toBeCalledWith({ name: 'my-name' });
expect(client.invoke).toBeCalledWith({ input1: 'a', input2: 'b' });
});
});
Unit test results with 100% coverage:
PASS src/stackoverflow/60008679/index.test.js (11.029s)
60008679
✓ should invoke (8ms)
✓ should handle error (4ms)
----------|----------|----------|----------|----------|-------------------|
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: 2 passed, 2 total
Snapshots: 0 total
Time: 12.314s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/60008679

Using Jest to test anonymous function inside 3rd party module

I have a pretty simple module that use pg (node-postgre lib) module,
I'd like to implement a Jest test and while mocking the pg module I would like to run it's callback function to see the console.log runs and my callback is being invoked
I have mocked the module and tried to spy and replace the 'query' method but it failed and crushed,
any Idea what am I doing wrong?
Test Subject:
import {Pool} from 'pg';
const pool = new Pool();
module.exports = {
query: (text, params, callback) => {
const start = Date.now();
return pool.query(text, params, (err, res) => {
const duration = Date.now() - start;
console.log('executed query', {text, duration, rows: res.rowCount});
callback(err, res);
});
}
};
Test:
jest.mock('pg');
import module from './index';
import { Pool } from 'pg'
beforeAll(() => {
Pool.mockImplementation(()=>{return jest.fn()});
});
it('callback is called', () => {
const cb = (err, res) => true;
const query = jest.spyOn(Pool, "query"); // <---- Not right, Error
query.mockImplementation((a,b,c) => c({},{}));
const resolve = module.query('QUERY TEXT', { a: 1, b: 2}, cb);
resolve(); // <---- Not what I expect
expect(cb).toBeCalled();
});
});
Error thrown:
Error: Cannot spy the query property because it is not a function; undefined given instead
20 | it('callback is called', () => {
21 | const cb = (err, res) => true;
> 22 | const query = jest.spyOn(Pool, "query");
| ^
23 | query.mockImplementation((a,b,c) => c({},{}));
24 | const resolve = module.query('QUERY TEXT', { a: 1, b: 2}, cb);
25 | resolve();
at ModuleMockerClass.spyOn (node_modules/jest-mock/build/index.js:697:15)
at Object.spyOn (src/db/index.test.js:22:24)
Thanks
Here is the unit test solution:
index.js:
import { Pool } from 'pg';
const pool = new Pool();
module.exports = {
query: (text, params, callback) => {
const start = Date.now();
return pool.query(text, params, (err, res) => {
const duration = Date.now() - start;
console.log('executed query', { text, duration, rows: res.rowCount });
callback(err, res);
});
}
};
index.spec.js:
import mod from '.';
import { Pool } from 'pg';
jest.mock('pg', () => {
const mPool = {
query: jest.fn()
};
return { Pool: jest.fn(() => mPool) };
});
const pool = new Pool();
afterEach(() => {
jest.resetAllMocks();
jest.restoreAllMocks();
});
it('callback is called', done => {
let queryCallback;
pool.query.mockImplementation((text, params, callback) => {
queryCallback = callback;
});
const logSpy = jest.spyOn(console, 'log');
const userCallback = jest.fn();
mod.query('text', 'params', userCallback);
const mRes = { rowCount: 1 };
queryCallback(null, mRes);
expect(pool.query).toBeCalledWith('text', 'params', queryCallback);
expect(userCallback).toBeCalledWith(null, mRes);
expect(logSpy).toBeCalledWith('executed query', { text: 'text', duration: expect.any(Number), rows: 1 });
done();
});
Unit test result with 100% coverage:
PASS src/stackoverflow/52831401/index.spec.js
✓ callback is called (15ms)
console.log node_modules/jest-mock/build/index.js:860
executed query { text: 'text', duration: 0, rows: 1 }
----------|----------|----------|----------|----------|-------------------|
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: 4.026s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/52831401

Categories

Resources