单元测试和模拟然后是承诺中的方法
问题描述:
如果有一个逻辑单元需要用各种顺序的承诺进行测试,那么怎样才能实际确定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();
});
});
答
作为@ roamer-1888表示该解决方案与调用承诺和在测试中完成调用有关。
//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", (done) => {
let fiddleService = new FiddleService();
fiddleService.doSomething({}).then(_ => {
expect(someService.asyncOperation2).toHaveBeenCalled();
done();
});
});
});
+0
我不知道我帮了很多,但嘿,很高兴得到提及,谢谢。 –
答
茉莉花不是我的技能集的主要部分,所以这是暂时提供。
我仍然认为你需要Promise.resolve()
而不是new Promise()
在两个地方,并认为你可以利用茉莉花在单个测试中处理多个expect()的能力,而不会丢失任何信息。
//test
describe("FiddleService",() => {
let someService;
beforeAll(() => {
someService = new SomeService();
spyOn(someService.asyncOperation1).and.returnValue(Promise.resolve({firstName: "Jan"}));
spyOn(someService.asyncOperation2).and.returnValue(Promise.resolve({age: 50}));
spyOn(someService.asyncOperation3);
});
it("should make three sequential async calls", (done) => {
let fiddleService = new FiddleService();
fiddleService.doSomething({}).then(_ => {
expect(someService.asyncOperation1).toHaveBeenCalled();
expect(someService.asyncOperation2).toHaveBeenCalled();
expect(someService.asyncOperation3).toHaveBeenCalled();
done();
});
});
});
这两个'new Promise(()=> ...)'表达式返回永远不会解析的promise。 'Promise.resolve(...)'在两个地方似乎更合适。 –