我們在用Jasmine測試異步代碼時遇到意想不到的行爲。據我們所知,當您使用done
函數時,直到完成執行纔會調用期望。但是,這不會發生,因爲第二個期望失敗,因此$ctrl.todos
分配從來沒有發生過用茉莉花測試異步函數
不工作測試
it('initializes the data when $onIinit', (done) => {
const expected = 'some result';
const response = Promise.resolve(expected);
spyOn(myService, 'getAll').and.returnValue(response);
// This method calls myService.getAll
$ctrl.$onInit();
expect(myService.getAll).toHaveBeenCalled();
expect($ctrl.todos).toEqual(false);
response.then(done);
});
輸出:預期不確定等於假
。另一方面,這是工作:
it('initializes the data when $onIinit', (done) => {
const expected = 'some result';
const response = Promise.resolve(expected);
spyOn(myService, 'getAll').and.returnValue(response);
// This method calls myService.getAll
$ctrl.$onInit();
expect(myService.getAll).toHaveBeenCalled();
response
.then(() => expect($ctrl.todos).toBe(expected))
.then(done);
});
輸出:檢驗合格
控制器的方法:
$ctrl.$onInit =() => {
myService.getAll().then((data) => {
$ctrl.todos = data;
});
};