Skip to content

Instantly share code, notes, and snippets.

@virgs
Last active January 20, 2023 19:25
Show Gist options
  • Save virgs/d9c50e878fc69832c01f8085f2953f12 to your computer and use it in GitHub Desktop.
Save virgs/d9c50e878fc69832c01f8085f2953f12 to your computer and use it in GitHub Desktop.
How to mock static methods and non static methods using Jest
export class MockedClass {
public instanceMethod(): string {
return "instance";
}
public static staticMethod(): string {
return "static";
}
}
import {MockedClass} from './mocked-class'
jest.mock('./mocked-class');
describe('TestClass', () => {
it ('should mock instance method', () => {
const expectedValue: string = 'instanceMocked'
MockedClass.mockImplementation(() => {
return {
instanceMethod: () => expectedValue
};
});
const actualValue: string = new TestClass().callStaticMethod();
expect(actualValue).toBe(expectedValue);
});
it ('should mock static method', () => {
const expectedValue: string = 'staticMocked'
MockedClass.staticMethod.mockImplementation(() => expectedValue);
const actualValue: string = new TestClass().callStaticMethod();
expect(actualValue).toBe(expectedValue);
});
});
import {MockedClass} from './mocked-class'
export class TestClass {
public callInstanceMethod(): string {
return new MockedClass().instanceMethod();
}
public callStaticMethod(): string {
return MockedClass.staticMethod();
}
}
@xuan9
Copy link

xuan9 commented Jun 25, 2021

Great example, thanks a lot. Guess MyClass in test-class.spec.ts is MockedClass?

@virgs
Copy link
Author

virgs commented Jun 25, 2021

Thanks. Yes, you're right. Fixed it and thanks again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment