這是我的測試:
it('add.user() should POST to /users/, failure', function() {
mockBackend.expectPOST("https://stackoverflow.com/users/", {username:'u', password: 'p', email: 'e', location: 'loc'}).respond(400, {msg: "bad request"});
BaseService.add.user({username:'u', password: 'p', email: 'e', location: 'loc'});
mockBackend.flush();
});
afterEach(function() {
mockBackend.verifyNoOutstandingExpectation();
mockBackend.verifyNoOutstandingRequest();
});
當我運行這個測試,我得到這個錯誤:
Chromium 53.0.2785 (Ubuntu 0.0.0) Factory: BaseService add.user() should POST to /users/, failure FAILED
[object Object] thrown
Error: [$rootScope:inprog] $digest already in progress
http://errors.angularjs.org/1.3.15/$rootScope/inprog?p0=%24digest
at /home/user/Documents/ebdjango/ebdjangoapp/static/js/angular.js:63:12
at beginPhase (/home/user/Documents/ebdjango/ebdjangoapp/static/js/angular.js:14820:15)
at Scope.$digest (/home/user/Documents/ebdjango/ebdjangoapp/static/js/angular.js:14262:9)
at Function.$httpBackend.verifyNoOutstandingExpectation (node_modules/angular-mocks/angular-mocks.js:1557:38)
at Object.<anonymous> (tests/test_base.js:61:21)
這是BaseService.add.user()
:
self.add = {
user: function(user) {
return $http.post("https://stackoverflow.com/users/", user)
.then(function successHandler(response) {
return $http.post("/custom-api-auth/login", user)
}).then(function successHandler(response) {
$window.location.href = "/";
// if there are errors, rewrite the error messages
}).catch(function rejectHandler(errorResponse) {
for (prop in errorResponse.data) {
if (prop == "email") {
errorResponse.data[prop] = "Please enter a valid email address.";
} else if (prop == "username") {
errorResponse.data[prop] = "Username can only contain alphanumeric characters and '.'";
} else if (prop == "password") {
errorResponse.data[prop] = "Please enter a valid password";
}
}
throw errorResponse;
};
如何防止$digest already in progress
錯誤的發生?
編輯:如果我刪除throw errorResponse;
,測試工作,但我需要throw errorResponse;
那裏,因爲我需要顯示在前端的錯誤(這另一個控制器需要照顧.. BaseService.add.user().catch()
基本上重寫應該在顯示的錯誤前端)。
編輯2:當錯誤消息指出at Object.<anonymous> (tests/test_base.js:61:21)
它指向的行:mockBackend.verifyNoOutstandingExpectation();
錯誤消息被截斷。請始終發佈它們。發佈的代碼中沒有任何內容會導致這種情況。該測試很可能與其他單位不夠隔離。如果應用程序中存在路由器,則應將其存起來。順便說一句,$ window.location本身是不好的,它會搞砸下一個測試,其中一個響應不會返回錯誤。 – estus
@estus我編輯的職位,以顯示完整的錯誤消息。另外,如果不是'$ window.location'來設置URL,我應該使用什麼呢?(在測試時,我想將URL設置爲任何特定的URL,並驗證URL在POST成功後更改。在實際應用程序中 - 未測試時 - 我使用$ window.location將用戶重定向到不同的URL ) – user2719875
你可以分享你的'mockBackend'嗎? – tanmay