如果有一个逻辑单元需要用各种顺序的承诺进行测试,那么怎样才能实际确定then(() => {})
函数中的逻辑?通过类似的设置,我会遇到第一次测试会通过但第二次测试没有通过的问题。我很好奇为什么匿名然后在执行块永远不会到达。单元测试和模拟然后是承诺中的方法
//Implementation
class FiddleService {
constructor(dependencies = {}) {
const { someService = new SomeService() } = dependencies;
this.someService = someService;
}
doSomething(params) {
this.someService.asyncOperation1(params).then((result) => {
...
//never gets called by spy in test
return this.someService.asyncOperation2(result.firstName);
}).then((result) => {
return this.someService.asyncOperation3(result.age);
});
}
}
//test
describe("FiddleService",() => {
let someService;
beforeAll(() => {
someService = new SomeService();
spyOn(someService.asyncOperation1).and
.returnValue(new Promise(() => {firstName: "Jan"});
spyOn(someService.asyncOperation2).and
.returnValue(new Promise(() => {age: 50});
spyOn(someService.asyncOperation3);
});
it("calls asyncOperation1",() => {
let fiddleService = new FiddleService();
fiddleService.doSomething({});
expect(someService.asyncOperation1).toHaveBeenCalled();
});
it("calls asyncOperation2",() => {
let fiddleService = new FiddleService();
fiddleService.doSomething({});
expect(someService.asyncOperation2).toHaveBeenCalled();
});
});
这两个'new Promise(()=> ...)'表达式返回永远不会解析的promise。 'Promise.resolve(...)'在两个地方似乎更合适。 –