- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我的目标是测试 API 调用,将延迟考虑在内。我的灵感来自 this post .
我设计了一个沙箱,其中模拟 API 需要 1000 毫秒来响应和更改全局变量 kết quả
的值。测试检查 500 毫秒后和 1500 毫秒后的值。
这是最后一个测试应该失败的代码:
let result: number;
const mockAPICall = (delay: number): Observable => {
console.log('API called');
return Observable.of(5).delay(delay);
};
beforeEach(() => {
console.log('before each');
});
it('time test', async(() => {
result = 0;
const delay = 1000;
console.log('start');
mockAPICall(delay).subscribe((apiResult: number) => {
console.log('obs done');
result = apiResult;
});
console.log('first check');
expect(result).toEqual(0);
thiết lập thời gian chờ(() => {
console.log('second check');
expect(result).toEqual(0);
}, 500
);
thiết lập thời gian chờ(() => {
console.log('third check');
expect(result).toEqual(0);
}, 1500
);
}));
最后的测试确实如预期的那样失败了,我在日志中得到了这个:
before each
API called
first check
second check
obs done
third check
现在,如果我在 beforeEach()
中放置一个 async()
:
beforeEach(async(() => {
console.log('async before each');
}));
,测试通过,我只在日志中得到这个:
async before each
API called
first check
没想到。为什么会有这种行为?幕后发生了什么?
注意:在以后的测试中,我将在 beforeEach()
中需要这个 async()
,因为我将使用 testBed
Và compileComponents
.
câu trả lời hay nhất
您的问题源于在测试期间使用区域的不幸边缘案例,并在 Angular 文档中进行了概述 đây .
Writing test functions with
xong()
, is more cumbersome thankhông đồng bộ
VàfakeAsync
. But it is occasionally necessary. For example, you can't callkhông đồng bộ
hoặcfakeAsync
when testing code that involves theintervalTimer()
or the RxJSdelay()
operator.
这与 rxjs
中计时器的实现有关,那里有很多好资料可以帮助您使用 TestSchedulers 测试 rxjs
代码,这些代码使用了一些这些运算符(如 trì hoãn
)。
对于您的情况,您可以选择重构您的测试以不使用 trì hoãn
运算符,或者您可以回退到 Jasmine 提供的 xong()
。
let result: number;
const mockAPICall = (delay: number): Observable => {
console.log('API called');
return Observable.of(0).delay(delay); // changed from 5 -> 0, to make tests pass
};
beforeEach(async(() => {
console.log('async before each');
}));
it('time test', done => async(() => {
result = 0;
const delay = 1000;
console.log('start');
mockAPICall(delay).subscribe((apiResult: number) => {
console.log('obs done');
result = apiResult;
});
console.log('first check');
expect(result).toEqual(0);
thiết lập thời gian chờ(() => {
console.log('second check');
expect(result).toEqual(0);
}, 500
);
thiết lập thời gian chờ(() => {
console.log('third check');
expect(result).toEqual(0);
done(); // indicate that the test is complete
}, 1500
);
})());
因为在 không đồng bộ
中使用 trì hoãn
存在问题,Jasmine 提前“结束”了测试——你看不到失败,但你也不会看到一些日志记录语句。
关于 Jasmine Angular : is there a conflict between async in beforeEach() and async in it()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49069658/
Tôi là một lập trình viên xuất sắc, rất giỏi!