【发布时间】:2015-05-29 09:26:44
【问题描述】:
我有一个帐户和用户工厂。现在我想测试帐户工厂。
在测试中我想检查是否调用了 new User() 并返回了假数据。
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
]
测试:
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 })
我总是: 错误:User() 方法不存在
这里是fiddle
当我删除间谍时,测试是绿色的,并且调用了 console.log。 当我添加 spyOn 时,我得到了错误。
如何进行测试以检查是否调用了新用户?
【问题讨论】:
-
您要求 Jasmine 监视
window对象的User方法:spyOn(window, 'User')。 -
我不知道有其他方法可以监视新用户,但窗口不知道用户。
-
创建
Account时,需要发送一个mockUser。 -
对不起,我不知道该怎么做
-
您必须使用
$provide来创建您的工厂。 stackoverflow.com/questions/14773269/…