Various Jest docs show creation of "automatic" mocks, "manual" mocks, or ES6 class mocks (which instantiate dependencies within the constructor).
But I want to use DI / IOC and inject dependencies into the ctor:
// IBar.ts <--- mock this
export default interface IBar {
/* ...methods... */
}
// Baz.ts <--- mock this
export default class Baz {
constructor(spam: Spam, ham: IHam) { /* ... */}
/* ...other methods... */
}
// Foo.ts <--- test this
export default class Foo {
constructor(bar: IBar, baz: Baz) { /* ... */}
/* ...other methods... */
}
So I want to do this in a test:
const barMock = jest.giveMeAMock("../../IBar"); // or jest.giveMeAMock<IBar>();
const bazMock = jest.giveMeAMock("./Baz"); // or jest.giveMeAMock<Baz>();
const foo = new Foo(bar, baz);
expect(foo.something()).toBe(true);
Is this possible with Jest?
(I used some TypeScript syntax above, but it's the same problem for JS/ES6 and TS.)
TypeScript interfaces just get compiled away when the code gets converted to JavaScript...
...but it's definitely possible for a
class
.You can auto-mock a module using
jest.mock
andJest
will keep the API surface of the module the same while replacing the implementation with empty mock functions:baz.js
foo.js
code.test.js