各种 Jest 文档显示了“自动”模拟、“手动”模拟或ES6级 https://jestjs.io/docs/en/es6-class-mocks.html模拟(在构造函数中实例化依赖项)。
但我想使用 DI / IOC 并将依赖项注入到 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... */
}
所以我想在测试中这样做:
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 来说也是同样的问题。)
当代码转换为 JavaScript 时,TypeScript 接口就会被编译掉......
...但这绝对是可能的class
.
您可以使用自动模拟模块jest.mock
and Jest
将保持模块的 API 表面相同,同时用空替换实现模拟函数 https://jestjs.io/docs/en/mock-function-api:
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();
// ...
}
}
代码.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!
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)