Ter*_*rry 47 jasmine angularjs karma-runner karma-jasmine
似乎承诺不会在Angular/Jasmine测试中解决,除非你强迫一个$scope.$digest()
.这是愚蠢的IMO,但很好,我有适用的工作(控制器).
我现在是这种情况是我有一个并不十分关心应用程序中的任何一个范围的服务,它的作用是从服务器返回的一些数据,但承诺似乎并没有被解决.
app.service('myService', function($q) {
return {
getSomething: function() {
var deferred = $q.defer();
deferred.resolve('test');
return deferred.promise;
}
}
});
Run Code Online (Sandbox Code Playgroud)
describe('Method: getSomething', function() {
// In this case the expect()s are never executed
it('should get something', function(done) {
var promise = myService.getSomething();
promise.then(function(resp) {
expect(resp).toBe('test');
expect(1).toEqual(2);
});
done();
});
// This throws an error because done() is never called.
// Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
it('should get something', function(done) {
var promise = myService.getSomething();
promise.then(function(resp) {
expect(resp).toBe('test');
expect(1).toEqual(2);
done();
});
});
});
Run Code Online (Sandbox Code Playgroud)
测试此功能的正确方法是什么?
编辑:解决方案供参考.显然,即使服务没有使用它,你也不得不注入和消化$ rootScope.
it('should get something', function($rootScope, done) {
var promise = myService.getSomething();
promise.then(function(resp) {
expect(resp).toBe('test');
});
$rootScope.$digest();
done();
});
Run Code Online (Sandbox Code Playgroud)
pko*_*rce 41
你需要注入$rootScope
你的测试并触发$digest
它.
mpm*_*mpm 12
总是有$ rootScope,使用它
inject(function($rootScope){
myRootScope=$rootScope;
})
....
myRootScope.$digest();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
26175 次 |
最近记录: |