0

I'm using Mocha, Chai, and Sinon to test my Angular code.

I have some code in a function called update I need to test

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++;

        });

All of that code is within the update function. This is all within a controller that I am currently testing.

When I call scope.update() in my test, I want to make sure that the scope.addTabletoScope(x) is called.

in a beforeEach before I run the tests, I have a spy

spy = sinon.spy(scope, 'addTabletoScope'); 

Because that function is bound to the scope.

Here's one test I've run.

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

This fails because spy.called is false.

Another thing I tried was

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

Which also doesn't work. Where am I going wrong with this?

Oscar McCullough
  • 365
  • 4
  • 17

1 Answers1

0

I figured it out quickly after looking through MochaJS docs.

If I have functions with promises or any async behavior, after I call the function that exhibits that behavior, I should pass the done parameter to the anonymous function in that test, and then call upon done like this:

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

This works.

Oscar McCullough
  • 365
  • 4
  • 17