【发布时间】:2017-08-01 18:00:39
【问题描述】:
我们在使用 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);
});
输出:预期未定义等于 false
另一方面,这是可行的:
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;
});
};
【问题讨论】:
标签: javascript angularjs unit-testing asynchronous jasmine