6

I have simple filter which depends of moment.js:

app.filter('fromNow', function() {
  return function(date) {
    return moment(date).fromNow();
  }
});

Have can i write unit test of this in jasmine ?

EDIT: now i have

ReferenceError: moment is not defined

when write like that:

describe("fromNow filter", function(){
 var moment;
 beforeEach(function(){
   module('reports');
   moment = jasmine.createSpy();
  });


  it("should output string when input string",
    inject(function(fromNowFilter) {
      fromNowFilter("string");
  }));
})
Bartek S
  • 532
  • 4
  • 19
  • 1 load the module 2 call the method 3 assert the result – Tim Apr 28 '14 at 09:23
  • 1
    but i want to mock moment.js since this is unit test – Bartek S Apr 28 '14 at 09:24
  • Have you googled 'jasmine mock service'? There are dozens of examples on the internet – Tim Apr 28 '14 at 09:27
  • 4
    You should not mock moment.js. In fact, you should never mock what you don't own. What happens if the moment js implementation changes in future. Your test will still succeed while the actual implementation will result different output. Check the discussions here: http://stackoverflow.com/questions/1906344/should-you-only-mock-types-you-own – Manoj Shrestha Dec 11 '15 at 16:41

1 Answers1

7

You need to add moment.js to the testing framework. I had the same problem and fixed adding the following line to my karma.conf.js

...files: [
   ....
    'app/bower_components/moment/moment.js',
    ....
    ],
.....
kamayd
  • 420
  • 6
  • 10
  • Although this would work; however, you should not be including any other units of code, you should use mocks - otherwise you are not testing a single unit which makes the tests less useful. – Seer Jan 07 '15 at 12:00
  • so this solution is almost good, to complete mock this service I need to prepare function with moment, and implement this function (object) as I need, for example as a empty object. But manoj-shrestha answere is also good from my point of view. – Bartek S Apr 20 '16 at 06:40