嘲笑具有DI依赖关系的类 [英] Jest mocking of classes with DI dependencies
问题描述
Various Jest docs show creation of "automatic" mocks, "manual" mocks, or ES6 class mocks (which instantiate dependencies within the constructor).
但是我想使用DI/IOC并将依赖项注入ctor:
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);
Jest有可能吗?
(我在上面使用了一些TypeScript语法,但是对于JS/ES6和TS来说是同样的问题.)
(I used some TypeScript syntax above, but it's the same problem for JS/ES6 and TS.)
推荐答案
当代码转换为JavaScript时,TypeScript接口只是被编译掉了.
TypeScript interfaces just get compiled away when the code gets converted to JavaScript...
...但是class
绝对有可能.
...but it's definitely possible for a class
.
您可以使用jest.mock
自动模拟模块,并且Jest
将使模块的API表面保持相同,同时用空的
You can auto-mock a module using jest.mock
and Jest
will keep the API surface of the module the same while replacing the implementation with empty mock functions:
baz.js
export default class Baz {
doSomething() {
throw new Error('the actual function throws an error');
}
}
foo.js
export default class Foo {
constructor(baz) {
this.baz = baz;
}
doSomething() {
// ...
this.baz.doSomething();
// ...
}
}
code.test.js
code.test.js
jest.mock('./baz'); // <= auto-mock the module
import Baz from './baz';
import Foo from './foo';
test('Foo', () => {
const baz = new Baz(); // <= baz is an auto-mocked instance of Baz
const foo = new Foo(baz);
foo.doSomething(); // (no error)
expect(baz.doSomething).toHaveBeenCalled(); // Success!
})
这篇关于嘲笑具有DI依赖关系的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!