Let\'s suppose I have the following class:
export default class Person {
constructor(first, last) {
this.first = first;
this.last = last
Not really answer the question, but I want to show a use case where you want to mock a dependent class to verify another class.
For example: Foo
depends on Bar
. Internally Foo
created an instance of Bar
. You want to mock Bar
for testing Foo
.
Bar class
class Bar {
public runBar(): string {
return 'Real bar';
}
}
export default Bar;
Foo class
import Bar from './Bar';
class Foo {
private bar: Bar;
constructor() {
this.bar = new Bar();
}
public runFoo(): string {
return 'real foo : ' + this.bar.runBar();
}
}
export default Foo;
The test:
import Foo from './Foo';
import Bar from './Bar';
jest.mock('./Bar');
describe('Foo', () => {
it('should return correct foo', () => {
// As Bar is already mocked,
// we just need to cast it to jest.Mock (for TypeScript) and mock whatever you want
(Bar.prototype.runBar as jest.Mock).mockReturnValue('Mocked bar');
const foo = new Foo();
expect(foo.runFoo()).toBe('real foo : Mocked bar');
});
});
See also jest.requireActual(moduleName)