Converting angular-seed jasmine unit tests to coff

2019-07-04 00:29发布

问题:

As an exercise, I am trying to convert the karma unit tests included in the angular-seed repo from js to coffee script. In particular, I am having problems with the tests/unit/directivesSpec.js test set, which defines a simple value service. Here is my coffee script code:

 1  describe 'directives', ->
 2  beforeEach module 'myApp.directives'
 3  
 4  describe 'app-version', ->
 5    it 'should print current version', ->
 6      module ($provide) ->
 7        $provide.value 'version', 'TEST_VER'
 8      inject ($compile, $rootScope) ->
 9        element = $compile('<span app-version></span>')($rootScope)
10        expect(element.text()).toEqual 'TEST_VER'

There seems to be a problem when the coffee script code is compiled around line 6 as this becomes:

module(function($provide) {
  return $provide.value('version', 'TEST_VER');
});

And causes my tests to fail with the error:

Error: [ng:areq] Argument 'fn' is not a function, got Object
http://errors.angularjs.org/1.2.4/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20Object
    at /Data/src/ngfrontend-seed/app/vendor/angular/angular.js:78:12
    at assertArg (/Data/src/ngfrontend-seed/app/vendor/angular/angular.js:1358:11)
    at assertArgFn (/Data/src/ngfrontend-seed/app/vendor/angular/angular.js:1368:3)

If I remove the return statement, the test runs fine. Referring to the example in the documentation, it's not immediately clear what the module function accepts as a return value, but the return statement seems to be breaking things.

Any ideas of how to fix this, or would it be sensible to stick to plain javascript when writing test specs?

回答1:

Coffeescript implicitly returns the last expression from each function.
But you can add an explicit empty return statement like this:

6      module ($provide) ->
7        $provide.value 'version', 'TEST_VER'
8        return

which will compile to:

module(function($provide) {
  $provide.value('version', 'TEST_VER'); //without return
});

See also this thread for some more information.