测试以确保函数中的承诺中的函数被调用

Testing to make sure that a function within a promise within a function is called?

本文关键字:函数 调用 承诺 测试 确保      更新时间:2023-09-26

我用Mocha、Chai和Sinon来测试我的Angular代码。

我有一些代码在一个名为update的函数中,我需要测试

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.addTabletoScope(x)。

每次在运行测试之前,我都有一个spy
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为假。

我尝试的另一件事是

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;
    })

这工作。