我有以下茉莉花测试:
it('should resolve promise',inject(function ($q,$rootScope) { function getPromise(){ var deferred = $q.defer(); setTimeout(function(){ deferred.resolve(true); },1000); return deferred.promise; } var p = getPromise(); var cb = jasmine.createSpy(); runs(function(){ expect(cb).not.toHaveBeenCalled(); p.then(cb); $rootScope.$apply(); }); waitsFor(function(){ return cb.callCount == 1; }); runs(function(){ expect(cb).toHaveBeenCalled(); $rootScope.$apply(); }); }));
我认为$rootScope.$apply应该解决所有未完成的承诺,但不知怎的,它不会在这个测试中发生.
如何在这样的测试中触发promise解析?请帮忙!
我认为$rootScope.$apply()在你的情况下很快被调用.这应该工作:
原文链接:https://www.f2er.com/angularjs/140891.htmlfunction getPromise(){ var deferred = $q.defer(); setTimeout(function(){ deferred.resolve(true); $rootScope.$apply(); },1000); return deferred.promise; }
更新
你可以注入mock $timeout
service并使用$timeout.flush()显式解决这个问题.
it('should resolve promise',$timeout,$rootScope) { function getPromise(){ var deferred = $q.defer(); $timeout(function(){ deferred.resolve(true); },1000); return deferred.promise; } // ... $timeout.flush(); // ...