3

I have the following test case:

it('should return id if the post is successful',function(){
       var result = {
               id : "123"
       };
        ctrl.saveCallback(result);
        expect(ctrl.method.id).to.equal("123");
    });

Where ctrl.saveCallback copies the result.id into the method.id on the ctrl and then shows the success banner. On the success banner, we are using the translate filter to translate the message before showing it.

Function:

.....
ctrl.method.id = result.id;
magicallyShowOnScreen($filter('translate')('MESSAGES.SUCCESS'));
....

magicallyShowOnScreen is a service that shows whatever string we pass onto the screen, and that has been injected into beforeEach.

Can someone please point in the right direction as to how should I test or mock out this $filter('translate') ?

danwellman
  • 9,068
  • 8
  • 60
  • 88
km1882
  • 740
  • 5
  • 22
  • You using Sinon, Chai? Can you show how you're injecting `magicallyShowOnScreen` in your `beforeEach`? – Phil May 20 '15 at 05:09

1 Answers1

1

Preface: I'm not familiar with Mocha.js or how one would create spies however you would still inject them or similar mock objects the same way as you would for other testing frameworks.

Below is a Jasmine example, I hope it helps.


When you bootstrap your module (using the module / angular.mocks.module) function, you should provide your own version of $filter which should be a mock / spy that returns another mock / spy. For example

var $filter, filterFn;
beforeEach(module('myModule', function($provide) {
    $filter = jasmine.createSpy('$filter');
    filterFn = jasmine.createSpy('filterFn');
    $filter.and.returnValue(filterFn);

    $provide.value('$filter', $filter);
});

Then, in your test, you can make sure $filter is called with the right arguments, eg

expect($filter).toHaveBeenCalledWith('translate');
expect(filterFn).toHaveBeenCalledWith('MESSAGE.SUCCESS');
expect(magicallyShowOnScreen).toHaveBeenCalled(); // assuming this too is a spy
Phil
  • 157,677
  • 23
  • 242
  • 245