Skip to content

Instantly share code, notes, and snippets.

@revolunet
Last active April 23, 2018 08:02
Show Gist options
  • Save revolunet/6722092 to your computer and use it in GitHub Desktop.
Save revolunet/6722092 to your computer and use it in GitHub Desktop.
Jasmine test angular-translate calls
/*
silly way to ensure $translate service has been called with correct key and arguments
*/
var $translate;
beforeEach(inject(function (_$translate_) {
$translate = function() {
$translate.spy.apply(this, arguments);
};
$translate.spy = function() {};
spyOn($translate, 'spy').andCallFake(function() {
// dummy
});
});
it('should call translate service with correct parameters', function() {
// check we call $translate('translation-key-to-check', {username: 'Bill Cosby'});
expect($translate.spy).toHaveBeenCalledWith('translation-key-to-check', {username: 'Bill Cosby'});
});
@adamdude828
Copy link

Thanks, I was looking for a hour on how to do this. I was looking for something more "angularish" but this will work.

@danielmbarlow
Copy link

Thanks. I think there is a missing ')' on line 14.

@ralfius
Copy link

ralfius commented Aug 10, 2016

not worked for me. Have used this code to mock $translate finally

  beforeEach(module('MODULE_NAME, ($provide) => {
    // emulation of making translate mock
    const injector = angular.injector(['ng']),
    $q = injector.get('$q');

    const $translateMock = jasmine.createSpy().and.callFake(() => $q.when());

    $translateMock.storageKey = () => '';
    $translateMock.storage = () => { get: () => ''; };
    $translateMock.preferredLanguage = function () {
      return 'en';
    };
    $translateMock.use = () => '';

    $provide.value('$translate', $translateMock);
  }));

  it('should have $translate called', inject(($translate) => {
   $translate();
    expect($translate).toHaveBeenCalled();
  }));

@BBlackwo
Copy link

Thanks @ralfius your code worked for me too :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment