To mock a provider

446 views Asked by At

I have a module that in its config uses a provider that I need to mock.

provider itself has register function that takes 2 arguments and $get function that returns an object, but that's not really important (I think) since I'd be mocking it anyway. Just in case here's the entire provider

module uses the provider like this:

angular.module('replenishment').config(configureReplenishmentColumnDef);

configureReplenishmentColumnDef.$inject = ['columnDefProvider'];
function configureReplenishmentColumnDef(columnDefProvider) {
   let config = {
      matchWhen: ((schema)=> _.get(schema, 'format') === 'replenishment'),
      $get: replenishmentColDef
   };

   columnDefProvider.register(config);
}

replenishmentColDef.$inject = ['$q', 'schema', 'medData'];
function replenishmentColDef($q, schema, medData) { 
  ....
}

I started putting together a spec like this (our tests written in CoffeeScript)

describe 'replenishment-module', ->

  columnDefProvider = undefined

  beforeEach ->
    module ($provide)->
      $provide.provider 'columnDef', ->
         @.register = sinon.spy()
         @.$get = sinon.spy()
         return // had to put an explicit return here, as @DTing suggested    

    module 'replenishment'

    inject ->

Now I don't know how to properly mock provider's methods. Can you guys please show me, maybe I need to use stubs instead of spies.

1

There are 1 answers

5
dting On

Try adding explict returns like this, I think you are getting a malformed function:

describe 'replenishment-module', ->

  columnDefProvider = undefined

  beforeEach ->
    module ($provide)->
      $provide.provider 'columnDef', ->
        @.register = sinon.spy()
        @.$get = sinon.spy()
        return        

    module 'replenishment'

    inject ->

I think this is what your javascript equivalent looks like:

beforeEach(function() {
  module(function($provide) {
    return $provide.provider('columnDef', function() {
      this.register = sinon.spy();
      return this.$get = sinon.spy();
    });
  });

which would make it so your Provider columnDef doesn't have a $get factory method:

function Something() {
  return this.get = function() {
    console.log("get");
  };
}

var something = new Something();
something.get();