我已将MyService
定义如下
export interface MyService {
doStuff(): Promise<any>;
}
消费MyClass
的和MyService
import {MyService} from "./my.service";
import {Observable} from "rxjs/Observable";
export class MyClass {
constructor(private myService: MyService) {}
useMyService(): Observable<boolean> {
return Observable.create(obs => {
this.myService.doStuff()
.then((res: any) => {
console.log("Promise resolved!");
obs.next(true);
})
.catch((err: any) => {
console.log("Promise rejected!");
obs.error(false);
})
});
};
}
此外,我有一个定义为
的接口MyModel
export interface MyModel {
someProperty: string;
}
现在我想编写一个测试,以便我可以使用TypeMoq模拟MyService
。所以我做了以下
describe('MyClass', () => {
it('useMyService returns true when myService returns true', (done) => {
let mockModel = TypeMoq.Mock.ofType<MyModel>();
mockModel.setup(x => x.someProperty).returns(() => "info");
let mockMyService = TypeMoq.Mock.ofType<MyService>();
mockMyService.setup(x => x.doStuff()).returns(() => Promise.resolve(mockModel.object));
let myClass = new MyClass(mockMyService.object);
myClass.useMyService().subscribe(
(result: boolean) => {
expect(result).toBeTruthy();
done();
},
(error: any) => {
expect(error).toBeFalsy();
done();
});
});
});
但是,如上所示,当提供TypeMoq模拟时,Promise.resolve(mockModel.object)
似乎永远无法解决,即我没有得到“Promise resolved!” (或“承诺拒绝!”)打印到控制台,茉莉花测试超时。
如果我将Promise.resolve(mockModel.object)
替换为Promise.resolve({ someProperty: 'info'})
,即
let mockMyService = TypeMoq.Mock.ofType<MyService>();
mockMyService.setup(x => x.doStuff()).returns(() => Promise.resolve({ someProperty: 'info'}));
然后测试工作(我将“Promise resolved!”打印到控制台)。为什么Promise.resolve()
在提供TypeMoq模拟时没有解决?
答案 0 :(得分:4)
根据作者的说法,这是“a limitation of the underlying technology”,显然不是他们打算在 TypeMoq 中纠正的内容。
提供了一种解决方法,涉及在承诺解析为的模拟上设置then()
方法存根:
mockModel.setup((x: any) => x.then).returns(() => undefined);
这是否有资格作为问题的解决方案似乎是一个意见问题。