Unit testing events with mocha - node.js

Not sure where to start or what is the best approach to testing the following code with mocha and chai:
module.exports = function trackCustomDyEvents(events){
let $;
trackEvents();
function trackEvents() {
events.forEach((event) => {
$(document).on(event.type, event.element, () => {
if (!event.predicate()) return;
window.DY.API('event', {
name: event.name
});
});
});
}
};

Here is the unit test solution, you need a stub library such as sinon.js and I assume you use jquery.
index.js:
window.DY = window.DY || {};
window.DY.API = function(event, obj) {
// Your real implementation
};
module.exports = function trackCustomDyEvents(events) {
const $ = require("jquery");
trackEvents();
function trackEvents() {
events.forEach((event) => {
$(document).on(event.type, event.element, () => {
if (!event.predicate()) return;
window.DY.API("event", {
name: event.name,
});
});
});
}
};
index.test.js:
const jsdom = require("jsdom");
const sinon = require("sinon");
const proxyquire = require("proxyquire");
describe("trackCustomDyEvents", () => {
before(() => {
const html = '<!doctype html><html><head><meta charset="utf-8">' + "</head><body></body></html>";
const url = "http://localhost";
const document = new jsdom.JSDOM(html, { url });
const window = document.window;
global.document = window.document;
global.window = window;
});
afterEach(() => {
sinon.restore();
});
it("should call DY.API", () => {
const onStub = sinon.stub().yields();
const jqueryStub = sinon.stub().callsFake(() => ({
on: onStub,
}));
const trackCustomDyEvents = proxyquire("./", {
jquery: jqueryStub,
});
const APISpy = sinon.stub(window.DY, "API");
const predicateStub = sinon.stub().returns(true);
const events = [
{ type: "click", element: "button", name: "a", predicate: predicateStub },
{ type: "submit", element: "form", name: "b", predicate: predicateStub },
];
trackCustomDyEvents(events);
sinon.assert.calledWithExactly(onStub.firstCall, "click", "button", sinon.match.func);
sinon.assert.calledWithExactly(onStub.secondCall, "submit", "form", sinon.match.func);
sinon.assert.calledTwice(predicateStub);
sinon.assert.calledWithExactly(APISpy.firstCall, "event", { name: "a" });
sinon.assert.calledWithExactly(APISpy.secondCall, "event", { name: "b" });
});
it("should not call DY.API", () => {
const onStub = sinon.stub().yields();
const jqueryStub = sinon.stub().callsFake(() => ({
on: onStub,
}));
const trackCustomDyEvents = proxyquire("./", {
jquery: jqueryStub,
});
const APISpy = sinon.stub(window.DY, "API");
const predicateStub = sinon.stub().returns(false);
const events = [
{ type: "click", element: "button", name: "a", predicate: predicateStub },
{ type: "submit", element: "form", name: "b", predicate: predicateStub },
];
trackCustomDyEvents(events);
sinon.assert.calledWithExactly(onStub.firstCall, "click", "button", sinon.match.func);
sinon.assert.calledWithExactly(onStub.secondCall, "submit", "form", sinon.match.func);
sinon.assert.calledTwice(predicateStub);
sinon.assert.notCalled(APISpy);
});
});
Unit test result with 100% coverage:
trackCustomDyEvents
✓ should call DY.API (76ms)
✓ should not call DY.API
2 passing (146ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 91.67 | 100 | |
index.js | 100 | 100 | 80 | 100 | |
index.test.js | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59569112

Related

How does one properly to unit test Joi Schemas validation?

I created a Joi validation schema that gets called in my routes. However when I run a code coverage that file is NOT being covered. So, I am trying to write a test for it.
Validator.js
const Joi = require('joi');
module.exports = {
validateExternalId: (schema, name) => {
return (req, res, next) => {
const result = Joi.validate({ param: req.params[name] }, schema);
if (result.error) {
return res.status(400).send(result.error.details[0].message);
}
next();
};
},
schemas: {
idSchema: Joi.object().keys({
param: Joi.string().regex(/^[a-zA-Z0-9]{20}$/).required()
})
}
};
Validator.test.js
const { validateExternalId, schemas } = require('../../src/helpers/validation');
const app = require('../../src/router')
const mockResponse = () => {
const res = {};
res.status = jest.fn().mockReturnValue(res);
res.json = jest.fn().mockReturnValue(res);
return res;
};
describe('Testing validateExternalId schema', () => {
it('It can validate the external Id Regex length', done => {
const req = {
params: [
{
extClientId: 'abcdefghij0123456789'
}
]
};
app.use('/token/:extClientId', validateExternalId(schemas.idSchema, 'extClientId');
// expect().toHaveBeenCalled();
});
});
Please Go Easy on ME... Here is my attempt on testing this Joi validator. I tried to but my expected wasn't working so I commented it out for now. any pointers would be appreciated. thank you
Here is the unit test solution:
validator.js:
const Joi = require('joi');
module.exports = {
validateExternalId: (schema, name) => {
return (req, res, next) => {
const result = Joi.validate({ param: req.params[name] }, schema);
if (result.error) {
return res.status(400).send(result.error.details[0].message);
}
next();
};
},
schemas: {
idSchema: Joi.object().keys({
param: Joi.string()
.regex(/^[a-zA-Z0-9]{20}$/)
.required(),
}),
},
};
validator.test.js:
const { validateExternalId, schemas } = require('./validator');
const Joi = require('joi');
describe('60730701', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should send error', () => {
const validationResults = { error: { details: [{ message: 'validation error' }] } };
const validateSpy = jest.spyOn(Joi, 'validate').mockReturnValueOnce(validationResults);
const mReq = { params: { extClientId: '123' } };
const mRes = { status: jest.fn().mockReturnThis(), send: jest.fn() };
validateExternalId(schemas.idSchema, 'extClientId')(mReq, mRes);
expect(validateSpy).toBeCalledWith({ param: '123' }, schemas.idSchema);
expect(mRes.status).toBeCalledWith(400);
expect(mRes.send).toBeCalledWith('validation error');
});
it('should pass the validation and call api', () => {
const validationResults = { error: undefined };
const validateSpy = jest.spyOn(Joi, 'validate').mockReturnValueOnce(validationResults);
const mReq = { params: { extClientId: '123' } };
const mRes = {};
const mNext = jest.fn();
validateExternalId(schemas.idSchema, 'extClientId')(mReq, mRes, mNext);
expect(validateSpy).toBeCalledWith({ param: '123' }, schemas.idSchema);
expect(mNext).toBeCalled();
});
});
unit test results with 100% coverage:
PASS stackoverflow/60730701/validator.test.js (9.96s)
60730701
✓ should send error (6ms)
✓ should pass the validation and call api (2ms)
--------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
validator.js | 100 | 100 | 100 | 100 |
--------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 11.647s, estimated 15s
source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60730701

How to mock a controller?

How to mock this I don't know. Can someone help me on this ?
I want to write the test case for this controller. But I am new to this so where to start and how to write the test case I don't understand.
import { Route } from '../common/ExpressWrapper';
import {partnerDao} from '../factory/AppFactory';
import { keysToLowerCase } from '../util/TpsUtil';
import ErrorResponse from '../models/common/ErrorResponse'
const constants = require('../constants');
const logger = require('../logger/index.ts')('controller/PartnerController');
const GetPartnerByPKController: Route = (req, res) => {
logger.debug("Entering GetPartnerByPKController()");
let uuid = req.params.uuid;
console.time("TimeTaken:DBCall:");
console.log("Entering GetPartnerByPKController()"+uuid);
partnerDao.getPartnerByUuid(uuid).then(result => {
if (result != undefined) {
res.status(200).send(result);
} else {
logger.info("Partner for the uuid:" + uuid + " was not found");
res.status(404).send(new ErrorResponse("Partner not found", "404.1.100", constants.ERROR_LINK + "404.1.100", []));
}
}).catch(error => {
console.log("Error in accessing GetPartnerByPK API", JSON.stringify(error))
logger.error("Error in accessing GetPartnerByPK API", JSON.stringify(error));
res.status(500).send(new ErrorResponse("Internal Server Error", "500.1.103", constants.ERROR_LINK + "500.1.103", [JSON.stringify(error.message)]));
});
console.timeEnd("TimeTaken:DBCall:");
logger.debug("Leaving GetPartnerByPKController()");
}
Here is the unit test solution:
controller.ts:
import { partnerDao } from "./AppFactory";
import ErrorResponse from "./ErrorResponse";
type Route = any;
const constants = {
ERROR_LINK: "ERROR_LINK",
};
export const GetPartnerByPKController: Route = async (req, res) => {
console.debug("Entering GetPartnerByPKController()");
let uuid = req.params.uuid;
console.time("TimeTaken:DBCall:");
console.log("Entering GetPartnerByPKController()" + uuid);
await partnerDao
.getPartnerByUuid(uuid)
.then((result) => {
if (result != undefined) {
res.status(200).send(result);
} else {
console.info("Partner for the uuid:" + uuid + " was not found");
res
.status(404)
.send(new ErrorResponse("Partner not found", "404.1.100", constants.ERROR_LINK + "404.1.100", []));
}
})
.catch((error) => {
console.log("Error in accessing GetPartnerByPK API", JSON.stringify(error));
console.error("Error in accessing GetPartnerByPK API", JSON.stringify(error));
res
.status(500)
.send(
new ErrorResponse("Internal Server Error", "500.1.103", constants.ERROR_LINK + "500.1.103", [
JSON.stringify(error.message),
]),
);
});
console.timeEnd("TimeTaken:DBCall:");
console.debug("Leaving GetPartnerByPKController()");
};
AppFactory.ts:
export const partnerDao = {
async getPartnerByUuid(id) {
return "real data";
},
};
ErrorResponse.ts:
export default class ErrorResponse {
public desc = "";
public args: any;
public code: string = "";
public message: string = "";
constructor(message, code, desc, args) {
this.message = message;
this.desc = desc;
this.args = args;
this.code = code;
}
}
controller.test.ts:
import { GetPartnerByPKController } from "./controller";
import { partnerDao } from "./AppFactory";
import sinon from "sinon";
import { expect } from "chai";
import ErrorResponse from "./ErrorResponse";
describe("GetPartnerByPKController", () => {
afterEach(() => {
sinon.restore();
});
it("should get parter by uuid correctly", async () => {
const mResponse = "fake data";
const getPartnerByUuidStub = sinon.stub(partnerDao, "getPartnerByUuid").resolves(mResponse);
const mReq = { params: { uuid: "123" } };
const mRes = { status: sinon.stub().returnsThis(), send: sinon.stub() };
await GetPartnerByPKController(mReq, mRes);
sinon.assert.calledWith(mRes.status, 200);
sinon.assert.calledWith(mRes.status().send, mResponse);
sinon.assert.calledWith(getPartnerByUuidStub, "123");
});
it("should 404", async () => {
const mResponse = undefined;
const getPartnerByUuidStub = sinon.stub(partnerDao, "getPartnerByUuid").resolves(mResponse);
const mReq = { params: { uuid: "123" } };
const mRes = { status: sinon.stub().returnsThis(), send: sinon.stub() };
await GetPartnerByPKController(mReq, mRes);
sinon.assert.calledWith(mRes.status, 404);
sinon.assert.calledWith(
mRes.status().send,
new ErrorResponse("Partner not found", "404.1.100", "ERROR_LINK" + "404.1.100", []),
);
sinon.assert.calledWith(getPartnerByUuidStub, "123");
});
it("should 500", async () => {
const mError = new Error("unknown error");
const getPartnerByUuidStub = sinon.stub(partnerDao, "getPartnerByUuid").rejects(mError);
const mReq = { params: { uuid: "123" } };
const mRes = { status: sinon.stub().returnsThis(), send: sinon.stub() };
await GetPartnerByPKController(mReq, mRes);
sinon.assert.calledWith(mRes.status, 500);
sinon.assert.calledWith(
mRes.status().send,
new ErrorResponse("Internal Server Error", "500.1.103", "ERROR_LINK" + "500.1.103", [
JSON.stringify(mError.message),
]),
);
sinon.assert.calledWith(getPartnerByUuidStub, "123");
});
});
Unit test result with coverage report:
GetPartnerByPKController
Entering GetPartnerByPKController()
Entering GetPartnerByPKController()123
TimeTaken:DBCall:: 21.633ms
Leaving GetPartnerByPKController()
✓ should get parter by uuid correctly
Entering GetPartnerByPKController()
Entering GetPartnerByPKController()123
Partner for the uuid:123 was not found
TimeTaken:DBCall:: 0.532ms
Leaving GetPartnerByPKController()
✓ should 404
Entering GetPartnerByPKController()
Entering GetPartnerByPKController()123
Error in accessing GetPartnerByPK API {}
Error in accessing GetPartnerByPK API {}
TimeTaken:DBCall:: 35.619ms
Leaving GetPartnerByPKController()
✓ should 500 (38ms)
3 passing (124ms)
--------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
--------------------|----------|----------|----------|----------|-------------------|
All files | 98.51 | 100 | 91.67 | 98.41 | |
AppFactory.ts | 50 | 100 | 0 | 50 | 3 |
ErrorResponse.ts | 100 | 100 | 100 | 100 | |
controller.test.ts | 100 | 100 | 100 | 100 | |
controller.ts | 100 | 100 | 100 | 100 | |
--------------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59319054

How to mock response from service for testing controller in typescript using Jest

I am testing a controller written in typescript using Jest. I try to mock the response of the service, but it does not work out.
this is my EmployeesController
import { EmployeesService } from '../services/employeeService';
import { IDBConnection } from '../config/IDBConnection';
export class EmployeesController {
private employeeService: EmployeesService;
constructor(dbConnection: IDBConnection) {
this.employeeService = new EmployeesService(dbConnection);
}
public async findAllEmployees(req: any, res: any) {
const numPerPage = +req.query.pagesize;
const page = +req.query.page;
try {
const count = await this.employeeService.findCount();
const results = await this.employeeService.findAll(numPerPage, page);
let totalEmployee = count[0].totalCount;
if (totalEmployee === 0) {
return res.status(404).json({
success: false,
message: 'Employee not found'
});
} else if (count && results) {
return res.status(200).json({
employees: results,
maxEmployees: totalEmployee
});
};
} catch {
res.status(500).json({
success: false,
message: 'Server error'
});
};
}
this is my EmployeesService
import { IDBConnection } from '../config/IDBConnection';
export class EmployeesService {
private connection: any;
constructor(connection: IDBConnection) {
this.connection = connection;
}
async findCount() {
const results = await this.connection.execute('SELECT count(*) as totalCount FROM EmployeeDB.Employees');
return results; // [ RowDataPacket { totalCount: 5 } ]
}
}
I can assume I am piping to it incorrectly from my service in test but I am not too sure. Is anyone able to help me?
this is my Employee.test
jest.mock('../../../services/employeeService');
import { EmployeesController } from '../../../controllers/employeeController';
import { EmployeesService } from '../../../services/employeeService';
describe('Employees', () => {
test('should get count of employees', async () => {
const getCount = jest.spyOn(EmployeesService.prototype, "findCount")
.mockImplementation(() => Promise.resolve([{totalCount: 5}]));
const mockResp = () => {
const res: any = {}
res.status = jest.fn().mockReturnValue(res)
res.json = jest.fn().mockReturnValue(res)
return res
}
const mockReq = () => {
const req: any = {}
req.query = jest.fn().mockReturnValue(req);
return req
}
const req = mockReq({
pagesize: 1,
page: 0
});
const res = mockResp();
await EmployeesController.prototype.findAllEmployees(req, res);
expect(getCount).toHaveBeenCalledTimes(1); // Received number of calls: 0
}
}
Here is the unit test solution:
controllers/employeeController.ts:
import { EmployeesService } from '../services/employeeService';
import { IDBConnection } from '../config/IDBConnection';
export class EmployeesController {
private employeeService: EmployeesService;
constructor(dbConnection: IDBConnection) {
this.employeeService = new EmployeesService(dbConnection);
}
public async findAllEmployees(req: any, res: any) {
const numPerPage = +req.query.pagesize;
const page = +req.query.page;
try {
const count = await this.employeeService.findCount();
const results = await this.employeeService.findAll(numPerPage, page);
let totalEmployee = count[0].totalCount;
if (totalEmployee === 0) {
return res.status(404).json({
success: false,
message: 'Employee not found',
});
} else if (count && results) {
return res.status(200).json({
employees: results,
maxEmployees: totalEmployee,
});
}
} catch {
res.status(500).json({
success: false,
message: 'Server error',
});
}
}
}
services/employeeService.ts:
import { IDBConnection } from '../config/IDBConnection';
export class EmployeesService {
private connection: any;
constructor(connection: IDBConnection) {
this.connection = connection;
}
async findCount() {
const results = await this.connection.execute('SELECT count(*) as totalCount FROM EmployeeDB.Employees');
return results; // [ RowDataPacket { totalCount: 5 } ]
}
async findAll(numPerPage, page) {
return [];
}
}
config/IDBConnection.ts:
export interface IDBConnection {}
Employee.test.ts:
import { EmployeesController } from './controllers/employeeController';
import { EmployeesService } from './services/employeeService';
jest.mock('./services/employeeService', () => {
const mEmployeesService = {
findCount: jest.fn(),
findAll: jest.fn(),
};
return { EmployeesService: jest.fn(() => mEmployeesService) };
});
describe('Employees', () => {
afterEach(() => {
jest.resetAllMocks();
});
test('should get count of employees', async () => {
const mIDBConnection = {};
const employeeService = new EmployeesService(mIDBConnection);
(employeeService.findCount as jest.MockedFunction<any>).mockResolvedValueOnce([{ totalCount: 5 }]);
(employeeService.findAll as jest.MockedFunction<any>).mockResolvedValueOnce([{ id: 1, name: 'john' }]);
const mReq = {
query: {
pagesize: 10,
page: 1,
},
};
const mRes = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
};
const employeesController = new EmployeesController(mIDBConnection);
await employeesController.findAllEmployees(mReq, mRes);
expect(employeeService.findCount).toHaveBeenCalledTimes(1);
expect(employeeService.findAll).toBeCalledWith(10, 1);
expect(mRes.status).toBeCalledWith(200);
expect(mRes.status().json).toBeCalledWith({ employees: [{ id: 1, name: 'john' }], maxEmployees: 5 });
});
});
Unit test result with coverage report:
PASS src/stackoverflow/59235639/Employee.test.ts (11.243s)
Employees
✓ should get count of employees (13ms)
-----------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------------------|----------|----------|----------|----------|-------------------|
All files | 88.89 | 66.67 | 100 | 86.67 | |
employeeController.ts | 88.89 | 66.67 | 100 | 86.67 | 18,29 |
-----------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 12.958s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59235639

can't mock constructor using sinon and proxyquire

I've looked at several similar questions but none of the cases fit my problem. I'm trying to mock a constructor, which I've done in other tests, but I can't get it to work in the case of using google-auth-library
code.js
const {OAuth2Client} = require('google-auth-library');
const keys = require('./oauth2.keys.json');
async function getRedirectUrl() {
const oAuth2Client = new OAuth2Client(
keys.installed.client_id,
keys.installed.client_secret,
keys.installed.redirect_uris[0]
);
const authorizeUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: 'https://www.googleapis.com/auth/bigquery',
prompt: 'consent'
});
return authorizeUrl;
}
test.js
let Code = require('../code.js');
describe('code', function() {
let generateUrlStub, tokenStub, mockClient;
before(async () => {
generateUrlStub = sinon.stub().returns('http://example.com');
tokenStub = sinon.stub().returns({tokens: 'tokens'});
mockClient = sinon.stub().returns({
generateAuthUrl: generateUrlStub,
getToken: tokenStub,
});
Code = proxyquire('../Code.js', {
'google-auth-library': mockClient,
});
});
it('should call generateAuthUrl', async function() {
const output = await Code.getRedirectUrl();
sinon.assert.called(generateUrlStub)
});
});
Here is the unit test solution:
const { OAuth2Client } = require("google-auth-library");
const keys = {
installed: {
client_id: "1",
client_secret: "client_secret",
redirect_uris: ["http://example.com/callback"]
}
};
async function getRedirectUrl() {
const oAuth2Client = new OAuth2Client(
keys.installed.client_id,
keys.installed.client_secret,
keys.installed.redirect_uris[0]
);
const authorizeUrl = oAuth2Client.generateAuthUrl({
access_type: "offline",
scope: "https://www.googleapis.com/auth/bigquery",
prompt: "consent"
});
return authorizeUrl;
}
module.exports = { getRedirectUrl };
index.spec.js:
const proxyquire = require("proxyquire");
const sinon = require("sinon");
const { expect } = require("chai");
describe("code", function() {
let generateUrlStub, tokenStub, code;
beforeEach(() => {
generateUrlStub = sinon.stub().returns("http://example.com");
tokenStub = sinon.stub().returns({ tokens: "tokens" });
code = proxyquire("./", {
"google-auth-library": {
OAuth2Client: sinon.stub().callsFake(() => {
return {
generateAuthUrl: generateUrlStub,
getToken: tokenStub
};
})
}
});
});
afterEach(() => {
sinon.restore();
});
it("should call generateAuthUrl", async function() {
const output = await code.getRedirectUrl();
expect(output).to.be.eq("http://example.com");
sinon.assert.called(generateUrlStub);
});
});
Unit test result with 100% coverage:
code
✓ should call generateAuthUrl
1 passing (216ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
index.spec.js | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/58955304

Mocking Inherited Classes with Jest

I am extending net.Socket. In doing so, I am overriding the connect method as follows.
class ENIP extends Socket {
constructor() {
super();
this.state = {
session: { id: null, establishing: false, established: false },
error: { code: null, msg: null }
};
}
connect(IP_ADDR) {
const { registerSession } = encapsulation; //returns a buffer to send
this.state.session.establishing = true;
return new Promise(resolve => {
super.connect(EIP_PORT, IP_ADDR, () => { // This is what i want to mock -> super.connect
this.state.session.establishing = false;
this.write(registerSession());
resolve();
});
});
}
}
I want to mock the underlying Socket class so that I can simulate super.connect. Having viewed Facebook's docs on the matter, I am unsure on how to proceed with developing tests for this class as all methods will extend super.someMethodToMock. Does anyone know an approach I should take? Please let me know if there are any clarifying details I can provide.
You can use jest.spyOn(object, methodName) to create mock methods on Socket.prototype.
E.g.
index.js:
import { Socket } from 'net';
const EIP_PORT = 3000;
const encapsulation = {
registerSession() {
return 'session';
},
};
export class ENIP extends Socket {
constructor() {
super();
this.state = {
session: { id: null, establishing: false, established: false },
error: { code: null, msg: null },
};
}
connect(IP_ADDR) {
const { registerSession } = encapsulation;
this.state.session.establishing = true;
return new Promise((resolve) => {
super.connect(EIP_PORT, IP_ADDR, () => {
this.state.session.establishing = false;
this.write(registerSession());
resolve();
});
});
}
}
index.test.js:
import { ENIP } from './';
import { Socket } from 'net';
describe('ENIP', () => {
afterAll(() => {
jest.restoreAllMocks();
});
describe('#connect', () => {
it('should pass', async () => {
const writeSpy = jest.spyOn(Socket.prototype, 'write').mockImplementation();
const connectSpy = jest.spyOn(Socket.prototype, 'connect').mockImplementationOnce((port, addr, callback) => {
callback();
});
const enip = new ENIP();
await enip.connect('localhost');
expect(writeSpy).toBeCalledWith('session');
expect(connectSpy).toBeCalledWith(3000, 'localhost', expect.any(Function));
});
});
});
unit test result with coverage report:
PASS src/stackoverflow/48888509/index.test.jsx (10.43s)
ENIP
#connect
✓ should pass (7ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.jsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 12.357s
source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/48888509

Resources