Javascript 测试以确保函数中的承诺内的函数被调用?
我用摩卡、柴和西农来测试我的角度代码 我需要测试一个名为update的函数中的一些代码Javascript 测试以确保函数中的承诺内的函数被调用?,javascript,angularjs,mocha.js,sinon,sinon-chai,Javascript,Angularjs,Mocha.js,Sinon,Sinon Chai,我用摩卡、柴和西农来测试我的角度代码 我需要测试一个名为update的函数中的一些代码 function update() //... Irrelevant code to the question asked DataService.getEventsData(query).then(function (res) { var x = res.results; addTabletoScope(x); // Want to c
function update()
//... Irrelevant code to the question asked
DataService.getEventsData(query).then(function (res) {
var x = res.results;
addTabletoScope(x); // Want to check that this is called.
vm.tableState.pagination.numberOfPages = Math.ceil(res.resultsFound / vm.tableState.pagination.number);
vm.isLoading = false;
vm.count++;
});
所有这些代码都在update函数中。这都在我目前正在测试的控制器中
在测试中调用scope.update时,我希望确保调用了scope.addTabletoScopex
在每次运行测试之前,我都有一个间谍
spy = sinon.spy(scope, 'addTabletoScope');
因为该函数绑定到范围
这是我做的一个测试
it('Expects adding to scope to be called', function(){
$httpBackend.whenPOST(APP_SETTINGS.GODZILLA_EVENTS_URL)
.respond(res.data);
scope.tableState = tableState;
scope.update();
$httpBackend.flush();
expect(spy.called).to.be.true;
})
此操作失败,因为spy.called为false
我试过的另一件事是
it('Expects adding to scope to be called', function(){
$httpBackend.whenPOST(APP_SETTINGS.GODZILLA_EVENTS_URL)
.respond(res.data);
scope.tableState = tableState;
scope.update();
scope.$apply();
$httpBackend.flush();
expect(spy.called).to.be.true;
})
这也不起作用。这件事我哪里做错了 在浏览了MochaJS文档后,我很快就找到了答案 如果我有带有承诺或任何异步行为的函数,在调用显示该行为的函数后,我应该在该测试中将done参数传递给匿名函数,然后像这样调用done:
it('Expects adding to scope to be called', function(done){
$httpBackend.whenPOST(APP_SETTINGS.GODZILLA_EVENTS_URL)
.respond(res.data);
scope.tableState = tableState;
scope.update();
done();
$httpBackend.flush();
expect(spy.called).to.be.true;
})
这很有效