How to mock nanoid for testing? - javascript

I'm trying to mock nanoid for my testing but it doesn't seem to be working.
my function
public async createApp(appDto: ApplicationDto): Promise<string> {
const appWithToken = { ...appDto, accessToken: nanoid() };
const application = await this.applicationModel.create(appWithToken);
return application.id;
}
My test:
beforeEach(() => {
mockRepository.create.mockResolvedValueOnce({ id: mockId });
});
test("creates application and returns an id", async () => {
const mockAppDto: ApplicationDto = { email: "123#mock.com" };
const application = await applicationService.createApplication(mockAppDto);
expect(mockRepository.create).toHaveBeenCalledWith(mockAppDto); //how do I mock the nanoid here?
expect(application).toBe(mockId);
});
So basically I'm struggling to figure out how to mock the nanoid which is generated inside the function.
I've tried the following at the top of the file:
jest.mock('nanoid', () => 'mock id');
however it doesn't work at all.
Any help would be appreciated!

You didn't mock the nanoid module correctly. It uses named exports to export the nanoid function.
Use jest.mock(moduleName, factory, options) is correct, the factory argument is optional. It will create a mocked nanoid function.
Besides, you can use the mocked function from ts-jest/utils to handle the TS type.
E.g.
Example.ts:
import { nanoid } from 'nanoid';
export interface ApplicationDto {}
export class Example {
constructor(private applicationModel) {}
public async createApp(appDto: ApplicationDto): Promise<string> {
const appWithToken = { ...appDto, accessToken: nanoid() };
const application = await this.applicationModel.create(appWithToken);
return application.id;
}
}
Example.test.ts:
import { nanoid } from 'nanoid';
import { Example, ApplicationDto } from './Example';
import { mocked } from 'ts-jest/utils';
jest.mock('nanoid');
const mnanoid = mocked(nanoid);
describe('67898249', () => {
afterAll(() => {
jest.resetAllMocks();
});
it('should pass', async () => {
mnanoid.mockReturnValueOnce('mock id');
const mockAppDto: ApplicationDto = { email: '123#mock.com' };
const mockApplicationModel = { create: jest.fn().mockReturnValueOnce({ id: 1 }) };
const example = new Example(mockApplicationModel);
const actual = await example.createApp(mockAppDto);
expect(actual).toEqual(1);
expect(mockApplicationModel.create).toBeCalledWith({ email: '123#mock.com', accessToken: 'mock id' });
});
});
test result:
PASS examples/67898249/Example.test.ts (9.134 s)
67898249
✓ should pass (4 ms)
------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
Example.ts | 100 | 100 | 100 | 100 |
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.1 s

Related

Mocking function object with jest

I currently have an object that is used to interact with my API api.js:
export var Auth = (function () {
var Login = async function(username, password) {
//Async login code for interacting with the API
};
return {
Login: Login
}
});
And this object is imported inside another file, login.js:
import * as API from './api';
export var LoginRequestHandler = function() {
//processess user input, then calls:
try {
await API.Auth().Login(username, password);
} catch(e) {
throw new Error(e);
}
This is my jest test:
import * as API from '../api';
import * as User from '../user';
jest.mock('../api');
const spy = jest.spyOn(API.Auth(), 'Login');
User.LoginRequestHandler().then(() => {
expect(spy).toHaveBeenLastCalledWith('theUsername', 'thePassword');
}).catch(error => console.log(error));
This is my mock file, __mock__/api.js:
export var Auth = (function () {
var Login = async function(username, password) {
return Promise.resolve(true);
};
return {
Login: Login
}
});
I retrieve theUsername and thePassword through document.getElementId() in the LoginRequestHandler and create my own DOM for the test above.
Adding console.log(username) in the LoginRequestHandler reveals that it is being called and is able to get the right values. Furthermore, adding a console.log(username) in API.Auth().Login also reveals that it is getting the right values as well. However, when I look at my test logs, I see: Number of calls: 0 for the mock function and the test results in errors.
I assume that I am trying to spy on the wrong function, and is there anyway that I can fix this?
Every time you call API.Auth(), it will return a new object which has a Login method. So, the object created in LoginRequestHandler function and created by jest.spyOn(API.Auth(), 'Login') statement in your test case are different. The spy is only added to the later one. The Login method in LoginRequestHandler function is not spied.
So, here I am going to use jest.mock() to mock the api.js module without putting mocked object to __mocks__ directory. E.g.
api.js:
export var Auth = function () {
var Login = async function (username, password) {};
return {
Login: Login,
};
};
user.js:
import * as API from './api';
export var LoginRequestHandler = async function () {
const username = 'theUsername';
const password = 'thePassword';
try {
await API.Auth().Login(username, password);
} catch (e) {
throw new Error(e);
}
};
user.test.js:
import * as API from './api';
import * as User from './user';
jest.mock('./api', () => {
const auth = { Login: jest.fn() };
return {
Auth: jest.fn(() => auth),
};
});
describe('61643983', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('should login', () => {
expect.assertions(2);
return User.LoginRequestHandler().then(() => {
expect(API.Auth).toBeCalledTimes(1);
expect(API.Auth().Login).toHaveBeenLastCalledWith('theUsername', 'thePassword');
});
});
it('should throw error', () => {
expect.assertions(4);
const mError = new Error('user not found');
API.Auth().Login.mockRejectedValueOnce(mError);
return User.LoginRequestHandler().catch((e) => {
expect(API.Auth).toBeCalled();
expect(API.Auth().Login).toHaveBeenLastCalledWith('theUsername', 'thePassword');
expect(e).toBeInstanceOf(Error);
expect(e.message).toMatch(/user not found/);
});
});
});
unit test results with 100% coverage:
PASS stackoverflow/61643983/user.test.js (11.507s)
61643983
✓ should login (5ms)
✓ should throw error (3ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
user.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 13.023s
source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61643983

Representing chained methods and members Typescript through Mocha tests

I am testing a node.js controller file using mocha and chai and i'm unable to mock out the response object in my test
TestController.ts
export class TestController {
static async getTest(req:any, res:any, next:object) {
console.log("Test");
//some code here
res.status(200).json(result.rows);
}
and this works perfectly fine when I call the API, returns the right response etc. But when I try to test this Controller, here is what I have for my test file
Test.ts
it('Get Test method', async function () {
let req = {params: {testid: 12345}};
let res:any = {
status: function() { }
};
res.json = '';
let result = await TestController.getTest(req, res, Object);
});
I am not sure how to represent the response object here. If I just declare the variable res in the following way
let res:any;
I see the following error in my test
TypeError: Cannot read property 'json' of undefined
I am not sure how my response data structure res should be for making this test work.
You should use sinon.stub().returnsThis() to mock the this context, it allows you to call chain methods.
E.g.
controller.ts:
export class TestController {
static async getTest(req: any, res: any, next: object) {
console.log('Test');
const result = { rows: [] };
res.status(200).json(result.rows);
}
}
controller.test.ts:
import { TestController } from './controller';
import sinon from 'sinon';
describe('61645232', () => {
it('should pass', async () => {
const req = { params: { testid: 12345 } };
const res = {
status: sinon.stub().returnsThis(),
json: sinon.stub(),
};
const next = sinon.stub();
await TestController.getTest(req, res, next);
sinon.assert.calledWithExactly(res.status, 200);
sinon.assert.calledWithExactly(res.json, []);
});
});
unit test results with 100% coverage:
61645232
Test
✓ should pass
1 passing (14ms)
---------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
controller.ts | 100 | 100 | 100 | 100 |
---------------|---------|----------|---------|---------|-------------------

Using Jest.fn() to see if s3.upload function was called...what am I doing wrong?

I am a bit new to testing and I have been stuck on this issue for quite some time. So I am trying to test a s3.upload() function to see if it called, not to see if it actually uploads the object. The only constraint is that I cannot use any npm packages to mock out the functionality of the s3 bucket.
I was trying to follow this tutorial (How to mock a function inside another function (which I am testing) using sinon?) that uses sinon as a stub, but instead use jest instead. Any help or guidance with issue is appreciated.
// function.js
const uploadToS3 = (params) => {
const response = s3.upload(params).promise();
return response;
}
// functions.test.js
describe("Lambda Handler Function", () => {
test('To test to see if the uploadToS3 function was called', () => {
const sampleParam = {
Bucket: 'BucketName',
Key: 'BucketKey.zip',
Body: 'SGVsbG8sIFdvcmxk'
}
expect(uploadToS3(sampleParam).response).toBeCalled()
})
})
You can use jest.mock(moduleName, factory, options) to mock aws-sdk.
E.g.
function.js:
import AWS from 'aws-sdk';
const s3 = new AWS.S3();
const uploadToS3 = async (params) => {
const response = await s3.upload(params).promise();
return response;
};
export { uploadToS3 };
function.test.js:
import { uploadToS3 } from './function';
import AWSMock from 'aws-sdk';
jest.mock('aws-sdk', () => {
const mS3 = { upload: jest.fn().mockReturnThis(), promise: jest.fn() };
return { S3: jest.fn(() => mS3) };
});
describe('60970919', () => {
it('should pass', async () => {
const mS3 = new AWSMock.S3();
const mResponse = { Bucket: 'xxx' };
mS3.upload({}).promise.mockResolvedValueOnce(mResponse);
const actual = await uploadToS3({});
expect(actual).toEqual(mResponse);
expect(mS3.upload).toBeCalledWith({});
expect(mS3.upload().promise).toBeCalled();
});
});
unit test results with 100% coverage:
PASS stackoverflow/60970919/function.test.js (13.818s)
60970919
✓ should pass (9ms)
-------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
function.js | 100 | 100 | 100 | 100 |
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 15.486s
source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60970919

Mocking a node module in a jest test

I have a Jest test that I am writing for a function which makes an API call. If the API call returns a 403, a function from a node module should be called. I am trying to test this using a mock jest function, but I cannot get the test to use the mocked version of the module I am making.
file.spec.js
import file from './file'
const mockedNodeModule = jest.genMockFromModule('nodeModule')
mockedNodeModule.namedExport = { logout: jest.fn() }
it('call returns a 403', async () => {
await file.apiCall('brand', 'entityType', 'name')
expect(mockedNodeModule.namedExport.logout).toHaveBeenCalled()
})
file.js
import { namedExport } from './nodeModule';
import api from './api';
const apiCall = () => {
return api.makeCall().then(
() => {},
(error) => {
if (error.status === 403) {
namedExport.logout();
}
},
);
};
export default { apiCall };
The test always fails when I check whether mockedNodeModule.namedExport.logout has been called. When I put a breakpoint on the line that it is called, it seems that the mocked version is not being used when the test is running (i.e. it is still using the module from my node_modules). I have also tried using jest.mock() as well, but the result is the same. Is there something wrong in the way that I am setting up the test? Can jest not mock node modules in cases like this?
jest.mock(moduleName, factory, options) should work.
E.g.
file.js:
import { namedExport } from './nodeModule';
import api from './api';
const apiCall = () => {
return api.makeCall().then(
() => {},
(error) => {
if (error.status === 403) {
namedExport.logout();
}
},
);
};
export default { apiCall };
api.js:
function makeCall() {}
export default { makeCall };
nodeModule.js:
export const namedExport = {
logout() {
console.log('real implementation');
},
};
file.test.js:
import file from './file';
import api from './api';
import { namedExport } from './nodeModule';
jest.mock('./nodeModule', () => {
const mNamedExport = {
logout: jest.fn(),
};
return { namedExport: mNamedExport };
});
jest.mock('./api', () => {
return { makeCall: jest.fn() };
});
describe('59831697', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('should handle error if http status equal 403', async () => {
const mError = { status: 403 };
api.makeCall.mockRejectedValueOnce(mError);
await file.apiCall();
expect(namedExport.logout).toHaveBeenCalledTimes(1);
});
});
Unit test results with coverage report:
PASS src/stackoverflow/59831697/file.test.js (13.506s)
59831697
✓ should handle error if http status equal 403 (7ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 50 | 66.67 | 100 | |
file.js | 100 | 50 | 66.67 | 100 | 8 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 15.448s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59831697

Chained API's and Jest expects

I currently have an express app that does a bunch of logic on a controller.
One of the steps is to insert a record to the DB ( It uses ObjectionJS models ).
let user = await this.User.query(trx).insert(userData);
In an attempt to mock out the model, I have done :
let mockUser = {
query: jest.fn(() => {
return mockUser;
}),
insert: jest.fn(() => {
return mockUser;
}),
toJSON: jest.fn()
};
With this, I wanted to do an assertion:
expect(mockUser.query().insert).toBeCalledWith({ some: 'data' });
It seems I have missed something. When I run the tests, the code would reach the mock function insert. But jest complaints
You could use mockFn.mockReturnThis() to return this context.
E.g.
index.js:
export async function main(User) {
const trx = 'the trx';
const userData = {};
let user = await User.query(trx).insert(userData);
return user.toJSON();
}
index.test.js:
import { main } from './';
describe('47953161', () => {
it('should pass', async () => {
let mockUser = {
query: jest.fn().mockReturnThis(),
insert: jest.fn().mockReturnThis(),
toJSON: jest.fn().mockResolvedValueOnce({ id: 1 }),
};
const actual = await main(mockUser);
expect(actual).toEqual({ id: 1 });
expect(mockUser.query).toBeCalledWith('the trx');
expect(mockUser.query().insert).toBeCalledWith({});
expect(mockUser.query().insert().toJSON).toBeCalledTimes(1);
});
});
unit test result with coverage report:
PASS src/stackoverflow/47953161/index.test.ts (10.41s)
47953161
✓ should pass (7ms)
----------|----------|----------|----------|----------|-------------------|
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: 12.783s, estimated 13s
source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/47953161

Categories

Resources