javascriptangularjsmeteorjasmineangular-mock

Testing a custom method for $state.go


I tried to test this code:

redireccion() {
this.$state.go('modifyLine', {lineId: this.look()._id});
}

look() {
return Entries.findOne({name: this.entry.name});
}

the code above method is ok (look), but for 'redireccion' I tried something like this and i got an error.

this is the code:

    describe('redireccion()', () => {
      beforeEach( inject(($state) => {
      spyOn($state, 'go');
      spyOn(controller, 'look');
      spyOn(Entries, 'findOne');
      }));

    it('should be a ... bla bla', () => {
    controller.redireccion();
    expect($state.go).toHaveBeenCalledWith('modifyLine', {lineId: });
    });
   });

This is an excerpt, because really I do not know how testing this.


Solution

  • I will try to give you an insight. You should try to make your tests isolated... That means that if you're testing your redirection, you can mock the look method since it's not relevant (for this specific test).

     describe('testing redirection()', () => {
           beforeEach( inject(($state) => {
                //here I'm saying that I'm spying every call to $state.go
                spyOn($state, 'go');
    
                //And here I'm that I'm not only spying every call to 
                //controller.look() but I'm also replacing the original
                //implementation with my fake one. Every call will basically 
                //return an object with id equals 10
                spyOn(controller, 'look').and.callFake(() => {
                     var mockedLine = {
                         _id: 10
                     };
                     return mockedLine;
                });
           }));
    
           it('should call state.go', () => {
                controller.redireccion();
    
                //if you just want to check if the method was called, do the following:
                expect($state.go).toHaveBeenCalled();
    
                //if you need to also check the arguments, try:
                var args = $state.go.mostRecentCall.args;
                expect(args[0]).toBe('modifyLine');
                expect(args[1].lineId).toBe(10);
           });
      });