Skip to content

Instantly share code, notes, and snippets.

@davidcsejtei
Created May 26, 2021 18:21
Show Gist options
  • Save davidcsejtei/7bb5aea077b5ab20aba1b2f196a4064f to your computer and use it in GitHub Desktop.
Save davidcsejtei/7bb5aea077b5ab20aba1b2f196a4064f to your computer and use it in GitHub Desktop.
Test private class method with Jest
import { Request, Response } from 'express';
import GetAllUsers from './getAllUsers';
describe('Get all users request', () => {
let mockRequest: Partial<Request>;
let mockResponse: Partial<Response>;
let responseObject = {};
beforeEach(() => {
mockRequest = {
};
mockResponse = {
statusCode: 0,
send: jest.fn().mockImplementation((result) => {
responseObject = result;
})
};
});
test('200 - users', async () => {
const expectedStatusCode = 200;
const expectedReponse = {
users: [
{
name: 'JOHN',
age: 30
},
{
name: 'Peter',
age: 40
}
]
};
const userRoute = new GetAllUsers();
let spy = jest.spyOn(userRoute, 'changeUserName' as any);
userRoute.handle(mockRequest as Request, mockResponse as Response);
expect(mockResponse.statusCode).toBe(expectedStatusCode);
expect(responseObject).toEqual(expectedReponse);
expect(spy).toHaveBeenCalledWith("John");
expect(spy).toHaveBeenCalledTimes(1);
});
});
import { Request, Response } from 'express';
class GetAllUsers {
public handle(request: Request, response: Response) {
const users = [
{
name: this.changeUserName('John'),
age: 30
},
{
name: 'Peter',
age: 40
}
]
response.statusCode = 200;
response.send({ users });
}
private changeUserName(userName: string) {
return userName.toUpperCase();
}
}
export default GetAllUsers;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment