Reputation: 759
I have an account and user factory. Now I want to test the account Factory.
In the test I want to check whether new User() was called and fake data is returned.
angular.module('app')
.factory 'Account', [ 'User', (User) ->
class @Account
constructor: (account) ->
@self = this
@user = new User(account.user_id)
]
.factory 'User', [ '$http', ($http) ->
class @User
constructor: (id)
$http.get('/user.json?id='+id)
.success (data) =>
//do something
.error (data) ->
//do something
]
Test:
describe 'app', ->
describe 'Account', ->
Account = undefined
User = undefined
beforeEach(module('app'))
beforeEach inject((_Account_, _User_) ->
Account = _Account_
User = _User_
)
describe 'initialize', ->
it 'should call new User', ->
spyOn(window, 'User').and.callFake( (value) ->
return value
)
account = new Account({ id: 1 })
I got always: Error: User() method does not exist
Here a fiddle
When I remove the spy the test is green and the console.log is called. When I add the spyOn, I got the error.
How do I make a test to check if the new User is called?
Upvotes: 1
Views: 1353
Reputation: 40296
The way to mock an Angular service (in JS, I do not speak CS):
describe('app', function() {
describe('Account', function() {
var Account, User;
// This is always first
beforeEach(module('app'));
// This ***HAS*** to go before the beforeEach(inject(...)) block
beforeEach(function() {
User = ...; // mock it as necessary, e.g. jasmine.createSpy('UserMock')
module(function($provide) {
$provide.value('User', User);
});
});
beforeEach(inject(function(_Account_) {
Account = _Account_;
}));
// Now the User is mocked
...
});
});
If the User
is mocked with jasmine.createSpy
, then the following fiddle demonstrates a successful test: http://jsfiddle.net/7Lveyb50/
Upvotes: 1