我創建了一個回傳 json 物件的簡單服務。
getCountries() {
return this.httpService.get('../../assets/countries.json');
}
考試
describe('TestServiceService', () => {
let service: TestServiceService;
let httpController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule]
});
httpController = TestBed.inject(HttpTestingController);
service = TestBed.inject(TestServiceService);
});
it('return countries', () => {
service.getCountries().subscribe(resp => {
expect(resp).toEqual({'test': 0});
});
const req = httpController.expectOne({
method: 'GET',
url: '../../assets/countries.json'
});
req.flush({'test': 1});
httpController.verify();
});
});
當我嘗試對其進行測驗時,它使用 Jasmine 運行良好,但是在將 Jest 設定為測驗運行程式后,測驗總是通過,盡管它們不正常。當我使用 Jest Runner 插件在 VS Code 中除錯測驗時,它會檢測到錯誤,但以正常方式運行測驗它可以通過。
更新:
使用回呼“完成”作為 temp_user 建議我得到一個超時錯誤。我可以修復它,設定更長的超時時間,比如 20 秒或更長時間。但是我不知道,我覺得這樣一個簡單的測驗有點過分了,對吧?
thrown: "Exceeded timeout of 5000 ms for a test.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
19 | });
20 |
> 21 | it('return countries', (done) => {
| ^
22 | service.getCountries().subscribe(resp => {
23 | expect(resp).toEqual({'test': 0});
24 | done();
有什么建議么?還有其他合適的方法嗎?謝謝
uj5u.com熱心網友回復:
您可以將 observable 轉換為 promise 并應用 fakeAsync/tick 來完成待處理的任務
it('return countries', fakeAsync(() => {
...
service.getCountries().subscribe.toPromise().then(resp => {
...
})
...
req.flush({'test': 1});
httpController.verify();
tick();
uj5u.com熱心網友回復:
那是因為您正在運行異步代碼,而 Jasmine 并不是開箱即用的。
it('return countries', (done) => { // Add a callback here
service.getCountries().subscribe(resp => {
expect(resp).toEqual({'test': 0});
done(); // Call the callback here
});
const req = httpController.expectOne({
method: 'GET',
url: '../../assets/countries.json'
});
req.flush({'test': 1});
httpController.verify();
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/481716.html
