1

I want to unit test my client side models/resources.

I use restangular and would like to mock it out and check/spy if the correct calls were made to restangular.

My resource:

module = angular.module 'myapp.core.resources'

class Messaging
  constructor: (@restangular) ->
    @resource = @restangular.all('messaging')

  send_to: (user, message) =>
    @resource.post(to: user.id, message: message)

module.service '$messaging', ['Restangular', Messaging]

My mock:

# Globally available
@restangularMock =
  one: jasmine.createSpy()
  all: (resource) ->
    post: jasmine.createSpy('post'),
    get: jasmine.createSpy('get')

My test:

# Set the global config before end of configuration lifecycle
angular.module('myapp.core.config').config (GlobalConfig) ->
  GlobalConfig.setBaseConfig
    api:
      baseUri: '/api',
      csrfTokens: {'messaging': 'abcdef'}

describe "Resources", ->
  beforeEach module ($provide)->
    $provide.value('Restangular', self.restangularMock)

  beforeEach module("myapp.core.resources")

  describe "#Messaging", ->
    messaging = null

    beforeEach inject ($messaging) ->
      messaging = $messaging

    it "sends a message to the given user id", ->
      messaging.send_to('test', 'message!')

      expect(self.restangularMock.all('messaging').post).toHaveBeenCalledWith(to: 'test', message: 'message!')

The error I get:

Error: [ng:areq] Argument 'fn' is not a function, got Object

Looks like the failure comes from loading the restangular module, where it gets the restangular provider object (ie this.$get = -> ...) and tried to run invoke().

Stan Bondi
  • 4,118
  • 3
  • 24
  • 35

1 Answers1

7

The code:

beforeEach module ($provide)->
    $provide.value('Restangular', self.restangularMock)

is converted by coffeescript to

beforeEach(module(function($provide) {
  return $provide.value('Restangular', self.restangularMock);
}));

And the callback function in 'module' should return undefined.

So, change code to:

beforeEach module ($provide)->
    $provide.value('Restangular', self.restangularMock)
    return

Converting angular-seed jasmine unit tests to coffeescript

Community
  • 1
  • 1
maarek_j
  • 86
  • 3