Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a filter used within a controller function

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') ?

like image 797
km1882 Avatar asked Jun 21 '26 04:06

km1882


1 Answers

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
like image 190
Phil Avatar answered Jun 23 '26 07:06

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!