我想测试以下服务:
"use strict";
const BASE_API = APP_CONF.baseApi;
export default function() {
"ngInject";
class API {
constructor() {
this.loading = false;
}
logout() {
this.loading = true;
return $http.post(`${BASE_API}/logout`)
.then(res => {
this.loading = false;
return res.data;
}, err => {
this.loading = false;
throw err;
});
}
}
return new API();
};
我的测试:
"use strict";
let baseApi = APP_CONF.baseApi;
describe("Auth service", function() {
let Auth;
beforeEach(angular.mock.module("app"));
beforeEach(angular.mock.inject(function(_Auth_) {
Auth = _Auth_;
}));
context("method LOGOUT", function() {
let $httpBackend;
beforeEach(angular.mock.inject(function(_$httpBackend_) {
$httpBackend = _$httpBackend_;
$httpBackend.whenPOST(`${baseApi}/logout`).respond(200, { data: "ok"});
}));
it("should change 'loading' flag", function() {
Auth.logout();
assert.isTrue(Auth.loading);
$httpBackend.flush();
assert.isFalse(Auth.loading);
});
});
});
但我的测试失败并出现以下错误:
Chrome 51.0.2704 (Linux 0.0.0) Auth service method LOGOUT should change 'loading' flag FAILED
Error: Unexpected request: GET http://localhost:3000/api/mailboxes
No more request expected
在解决路由后调用此请求:
"use strict";
export function config($locationProvider, $stateProvider, $urlRouterProvider) {
"ngInject";
$urlRouterProvider.otherwise("404");
$locationProvider.html5Mode(true);
$stateProvider
.state("404", {
url: "/404",
template: `<view-404 class="v-404" />`
})
.state("home", {
url: "/",
template: `<view-home class="v-home" />`,
resolve: {
mailboxes: function(MailboxesApi, MailboxesStore, $state) {
"ngInject";
return MailboxesApi.getAll() // THIS LINE ACTIVATES UNEXPECTED REQUEST
.then(mailboxes => {
MailboxesStore.set(mailboxes);
let inbox = MailboxesStore.getByName("inbox");
if (inbox) {
$state.go("cabinet.mailbox", { mailboxid: inbox._id });
} else {
$state.go("cabinet.mailbox", { mailboxid: MailboxesStore.getByIndex(0)._id });
}
});
}
}
});
};
export function run($transitions) {
"ngInject";
$transitions.onError({ to: "*" }, (ErrorHandler, $error$) => {
"ngInject";
ErrorHandler.handle($error$);
});
};
我注意到在我的测试中调用了$ httpBackend.flush()后,状态'home'被激活了。为什么会这样?
我的依赖项:
答案 0 :(得分:2)
在查看错误详细信息后,似乎是正常的执行流程。刷新(/ logout /)后,它会根据您的项目路由逻辑重定向到主视图。但是,当它到达家庭时,它与邮箱API有关,并期望再进行一次httpbackend(GET)模拟。
我相信你应该在你的测试用例中添加一行类似下面的行
$httpBackend.whenGET('url').respond(200, { data: "ok"});