Skip to content

Instantly share code, notes, and snippets.

@Umkus
Last active November 2, 2021 10:31
Show Gist options
  • Save Umkus/f9f77b71a67264a9b6c0fc6d41d659bf to your computer and use it in GitHub Desktop.
Save Umkus/f9f77b71a67264a9b6c0fc6d41d659bf to your computer and use it in GitHub Desktop.
Mocking and testing a class (static, instance and constructor methods) in Jest (Typescript)
import { handler } from '../src/app'; // Actual part that will be tested
import { Model } from '../src/module'; // A module that will actually be imported as a mock object
jest.mock('../src/module'); // Jest will automatically hoist jest.mock calls to the top of the module (before any imports)
afterEach(() => { // Resetting the state after each test
jest.resetAllMocks();
jest.resetModules();
});
const input = {
id: 'test',
name: 'Mike',
};
describe('Mocking a class usage', () => {
it('Should test a static method call', async () => {
// Mocking the return of the call
(Model.findOne as jest.Mock).mockResolvedValue({});
await handler(input); // Calling the testable part
// Asserting a static method call
expect(Model.findOne).toHaveBeenCalledWith(expect.objectContaining({ id: input.id }));
});
it('Should test an instance method call', async () => {
await handler(input); // Calling the testable part
// Asserting an instance method call by accessing the prototype
expect(Model.prototype.save).toHaveBeenCalled();
});
it('Should test a constructor', async () => {
await handler(input); // Calling the testable part
// Asserting the class constructor
expect(Model).toHaveBeenCalledWith(expect.objectContaining({ name: input.name }));
});
it('Should test failure of instance method', async () => {
// Mocking an exception being thrown from an instance method
(Model.prototype.save as jest.Mock).mockRejectedValue(new Error('Something went wrong'));
// Asserting that the rejection happened
await expect(handler(input)).rejects.toThrow(Error);
// Asserting an instance method call by accessing the prototype
expect(Model.prototype.save).toHaveBeenCalled();
});
});
import { Model } from '../src/module'; // Importing a 3rd party module that needs to be mocked out
export async function handler(input: any): Promise<void> {
const item = Model.findOne({ id: input.id }); // Calling a static method
const instance = new Model({ name: input.name }); // Creating a class instance
instance.save(); // Calling an instance method
}
export class Model {
constructor(values: any) {
console.log('Creating an instance', values);
}
static findOne(filter: any): any {
console.log('Finding an item', filter);
return {
id: 'example',
};
}
save(): boolean {
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment