0
我是TDD的新手,正在測試一個authInterceptor(我有chai/mocha/sinon可用於我)角js,它有兩個函數,一個請求和一個responseError 。我成功測試了請求函數,但我不知道如何(掃描文檔)嘲笑401(未授權)錯誤。這裏是攔截器:角js karma/chai - 模擬授權錯誤
export default function AuthInterceptor($q, $injector, $log) {
'ngInject';
return {
request(config) {
let AuthService = $injector.get('AuthService');
if (!config.bypassAuthorizationHeader) {
if (AuthService.jwtToken) {
config.headers.Authorization = `Bearer ${AuthService.jwtToken}`;
} else {
$log.warn('Missing JWT', config);
}
}
return config || $q.when(config);
},
responseError(rejection) {
let AuthService = $injector.get('AuthService');
if (rejection.status === 401) {
AuthService.backToAuth();
}
return $q.reject(rejection);
}
};
}
這是我的四個測試。前三「這是塊順利過關,第四個是我在哪裏卡住了,我已經加入的「它」塊註釋:
import angular from 'angular';
import AuthInterceptor from './auth.interceptor'
describe('Auth interceptor test',() => {
describe('AuthInterceptor test',() => {
let $httpBackend, $http, authInterceptor = AuthInterceptor();
beforeEach(angular.mock.module(($httpProvider, $provide) => {
$httpProvider.interceptors.push(AuthInterceptor);
$provide.factory('AuthService',() => ({
jwtToken: "hello",
backtoAuth: angular.noop
}));
}));
beforeEach(inject(function($injector) {
$httpBackend = $injector.get('$httpBackend');
$http = $injector.get('$http');
}))
it('should have a request function',() => {
let config = {};
expect(authInterceptor.request).to.be.defined;
expect(authInterceptor.request).to.be.a('function');
})
it('the request function should set authorization headers', (done) => {
$httpBackend.when('GET', 'http://jsonplaceholder.typicode.com/todos')
.respond([{
id: 1,
title: 'Fake title',
userId: 1
}]);
$http.get('http://jsonplaceholder.typicode.com/todos').then(function(transformedResult) {
expect(transformedResult.config.headers.Authorization).to.be.defined;
expect(transformedResult.config.headers.Authorization).to.contain('Bearer')
done();
})
$httpBackend.flush();
});
it('should have a responseError function',() => {
expect(authInterceptor.responseError).to.be.defined;
expect(authInterceptor.responseError).to.be.a('function');
//TODO: test return value
// see that AuthService.backToAuth()
})
it('the error function should call backtoAuth', (done) => {
//a url that doesn't give me a 401 like I'm hoping.
$httpBackend.when('POST', 'https://wwws.mint.com/overview.event').respond([
//what do I do here?
])
$http.post('https://wwws.mint.com/overview.event').then(function(transformedResult) {
console.log("success", transformedResult);
done();
}, function(error){
// I can't seem to get in here. if I can, the responseError should be called, which in turn calls backToAuth...
console.log("error", error);
done();
})
$httpBackend.flush();
});