【发布时间】:2016-04-26 01:26:27
【问题描述】:
我想知道是否可以在测试中使用 async/await 执行类似的操作。
有了常规的 Promise,我可以像这样在单元测试中模拟一个 Promise。
class Foo {
fn() {
this.someService.someFn().then((data) => this.data = data);
}
}
describe("something", function() {
beforeEach(function() {
this.instance = new Foo();
// Can this part be mocked out with the same idea, when someService.someFn is async fn
this.instance.someService = {
someFn: function() {
return {
then: function(cb) {
cb("fake data");
}
}
}
}
this.instance.fn();
});
it("a test", function() {
expect(this.instance.data).toBe("fake data");
});
});
(如果我覆盖承诺,我就不必处理冲洗或类似的事情。) 但是现在,当 fn() 会变成这个的时候
class Foo {
async fn() {
try {
this.data = await this.someService.somefn();
} catch() {
}
}
}
我在 beforeEach 中所做的覆盖将不再起作用。 所以我的问题是......我可以做一些类似我用异步/等待代码样式覆盖承诺的事情吗?
这里的想法是我想模拟外部依赖项我正在单元测试可能使用的函数,例如“someService”。在那个特定的单元测试中,我希望 someService.someFn 能够正常工作,并且我可以模拟它的响应。其他测试检查“someFn”的有效性。
【问题讨论】:
标签: javascript async-await ecmascript-2017