Last active
January 20, 2023 19:25
-
-
Save virgs/d9c50e878fc69832c01f8085f2953f12 to your computer and use it in GitHub Desktop.
How to mock static methods and non static methods using Jest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class MockedClass { | |
public instanceMethod(): string { | |
return "instance"; | |
} | |
public static staticMethod(): string { | |
return "static"; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {MockedClass} from './mocked-class' | |
export class TestClass { | |
public callInstanceMethod(): string { | |
return new MockedClass().instanceMethod(); | |
} | |
public callStaticMethod(): string { | |
return MockedClass.staticMethod(); | |
} | |
} |
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
Great example, thanks a lot. Guess MyClass in test-class.spec.ts is MockedClass?