Testing a filter used in 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 it ctrl.saveCallback
copies result.id
in method.id
on ctrl
and then shows a banner of success. On the success banner, we use a filter translate
to translate the message before showing it.
Functions:
.....
ctrl.method.id = result.id;
magicallyShowOnScreen($filter('translate')('MESSAGES.SUCCESS'));
....
magicallyShowOnScreen
is a service that shows any line that we pass to the screen that was injected into the beforeEach.
Can anyone point out the right direction as to how I should test or mock this $filter('translate')
?
source to share
Foreword: I am not familiar with Mocha.js or how to create spies, but you still add them or similar mock objects in the same way as for other test frameworks.
Below is an example of Jasmine, I hope it helps.
When you load your module (using the module
/ function angular.mocks.module
), you must provide your own version $filter
, which should be a mock / spy that returns a different 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 that it $filter
is called with the correct arguments like
expect($filter).toHaveBeenCalledWith('translate');
expect(filterFn).toHaveBeenCalledWith('MESSAGE.SUCCESS');
expect(magicallyShowOnScreen).toHaveBeenCalled(); // assuming this too is a spy
source to share