主要问题是如何测试Promise完成后执行的预期操作,例如测试组件是否在收到某些远程内容后正确更新其状态.
在下面的规范中,dealWithIt()
模拟为响应完成的promise而执行的逻辑(它更新变量并触发"另一个异步事件").
it('Promises fulfilled by flushMicrotasks',fakeAsync((): void => {
let x = 1;
let y = 2;
let dealWithIt = function(p:Promise<number>) {
p.then( v => {
x = v;
Promise.resolve(v).then( v=> {y = v+1; });
});
};
let p = Promise.resolve(y);
dealWithIt(p);
flushMicrotasks();
//valid if promise handling completed
expect(x).toBe(2);
expect(y).toBe(3);
}));
it('Promises fulfilled by tick',fakeAsync((): void => {
let x = 1;
let y = 2;
let dealWithIt = function(p:Promise<number>) {
p.then( v => {
x = v; …
Run Code Online (Sandbox Code Playgroud) 我正在试图弄清楚fakeAsync的tick()
方法与堆栈溢出的done()
一些答案所建议的区别.
使用tick()
我们可以模拟超时,但我们可以完成相同的使用done()
吗?
为什么angular认为它比使用或更可行的方法?async
fakeAsync
举个例子.
这个方法对我有用......
it("Should display names",(done:any) => {
component.names = [
{
"firstname": "abc",
"lastname": "max"
},
{
"firstname": "def",
"lastname": "max"
},
];
done();
fixture.detectChanges();
let wrapBox = fixture.debugElement.queryAll(By.css('.wrapBox'));
console.log(wrapBox);
});
Run Code Online (Sandbox Code Playgroud)
但是以下方法返回' 6 timer(s) still in queue
'错误...
it("Should display names",fakeAsync(() => {
component.names = [
{
"firstname": "abc",
"lastname": "max"
},
{
"firstname": "def",
"lastname": "max"
},
];
tick();
fixture.detectChanges();
let wrapBox …
Run Code Online (Sandbox Code Playgroud)