다이제스트를 강제하는 $scope가 없을 때 AngularJS, Jasmine 2.0의 약속을 어떻게 해결합니까?
Angular/Jasmin 테스트에서는 강제로 를 실행하지 않으면 약속이 해결되지 않는 것 같습니다.이것은 바보 같은 IMO이지만, 괜찮습니다.필요한 경우(컨트롤러) 작업을 하고 있습니다.
현재 상황은 어플리케이션의 범위 따위는 신경 쓰지 않고 서버에서 데이터를 반환하는 서비스뿐이지만 약속은 해결되지 않는 것 같습니다.
app.service('myService', function($q) {
return {
getSomething: function() {
var deferred = $q.defer();
deferred.resolve('test');
return deferred.promise;
}
}
});
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();
});
});
});
이 기능을 테스트하는 올바른 방법은 무엇입니까?
Edit: 참조용 솔루션.서비스가 $rootScope를 사용하지 않더라도 $rootScope를 주입하고 다이제스트해야 하는 것 같습니다.
it('should get something', function($rootScope, done) {
var promise = myService.getSomething();
promise.then(function(resp) {
expect(resp).toBe('test');
});
$rootScope.$digest();
done();
});
주사를 놓으셔야 합니다.$rootScope테스트와 트리거로$digest그 위에 올려놔요.
$rootScope는 항상 존재합니다.사용하세요.
inject(function($rootScope){
myRootScope=$rootScope;
})
....
myRootScope.$digest();
그래서 오후 내내 이것과 씨름하고 있어요.이 글을 읽고 나도 뭔가 잘못된 것이 있다고 느꼈는데, 알고 보니 있다.위의 답변 중 어디에, 왜 사용해야 하는지에 대한 명확한 설명은 없습니다.$rootScope.$digest그래서 제가 생각해낸 건 이렇습니다.
우선 왜?를 사용해야 합니다.$rootScope.$digest비콜백 이벤트 또는 콜백에서 응답할 때 항상 사용할 수 있습니다.여기에는 순수 DOM 이벤트, jQuery 이벤트 및 기타 서드파티 Promise 라이브러리가 포함됩니다.$q각도의 일부입니다.
두 번째로 어디?네 코드로는, 네 코드로는주사할 필요가 없다$rootScope실제 각도 서비스에서만 필요합니다.위의 모든 것이 답이 무엇인지 명확히 하지 못하는 곳이 바로 그곳이라고 그들은 보여준다.$rootScope.$digest테스트에서 호출된 대로.
나는 이것이 같은 문제를 안고 있는 다음에 오는 사람에게 도움이 되기를 바란다.
갱신하다
어제 부결되었을 때 이 게시물을 삭제했습니다.오늘 저는 위의 답변들을 사용하려다 이 문제가 계속 발생하였습니다.그래서 평판 포인트를 희생하고 답변을 대기하고 있기 때문에 삭제하지 않고 있습니다.
이것은 각도가 아닌 이벤트 핸들러에서 필요한 것입니다.또한 $q를 사용하여 Jasmine으로 테스트하려고 합니다.
something.on('ready', function(err) {
$rootScope.$apply(function(){deferred.resolve()});
});
경우에 따라서는 $timeout으로 포장해야 할 수도 있습니다.
something.on('ready', function(err) {
$timeout(function(){
$rootScope.$apply(function(){deferred.resolve()});
});
});
한 장 더.문의하고 있는 원래의 문제 예에서는
done전화해야 요.done내 of의thenmethod "method"( "method"(또는 "method")catch★★★★★★★★★★★★★★★★★」finally약속의 경우 해결됩니다.해결되기 에 콜하고 그에, 「」가 발생하고 .it종료하는 절.
각도의 문서로부터.
https://docs.angularjs.org/api/ng/service/$q
it('should simulate promise', inject(function($q, $rootScope) {
var deferred = $q.defer();
var promise = deferred.promise;
var resolvedValue;
promise.then(function(value) { resolvedValue = value; });
expect(resolvedValue).toBeUndefined();
// Simulate resolving of promise
deferred.resolve(123);
// Note that the 'then' function does not get called synchronously.
// This is because we want the promise API to always be async, whether or not
// it got called synchronously or asynchronously.
expect(resolvedValue).toBeUndefined();
// Propagate promise resolution to 'then' functions using $apply().
$rootScope.$apply();
expect(resolvedValue).toEqual(123);
}));
언급URL : https://stackoverflow.com/questions/24021031/how-to-resolve-promises-in-angularjs-jasmine-2-0-when-there-is-no-scope-to-for
'programing' 카테고리의 다른 글
| 입력 유형=파일이 반응 구성 요소에서 동일한 파일을 선택하도록 허용하는 방법 (0) | 2023.03.16 |
|---|---|
| Mongoose 'static' 메서드 대 'instance' 메서드 (0) | 2023.03.16 |
| 데이터 소스의 스프링 부트 자동 구성 (0) | 2023.03.16 |
| 동적 키, 값 쌍을 JavaScript 배열 또는 해시 테이블에 추가 (0) | 2023.03.16 |
| 기능적 리액트 컴포넌트에서 오류 경계를 활용하는 방법은 무엇입니까? (0) | 2023.03.16 |