angular js karma/chai - mock an authorization error

雨燕双飞 提交于 2019-12-12 03:38:46

问题


I am new to TDD and am testing an authInterceptor (I have chai/mocha/sinon available to me) in angular js, which has two functions, a request, and a responseError. I successfully tested the request function, but I don't know how (scoured the docs) to mock a 401 (unauthorized) error. Here is the interceptor:

 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);
    }
  };

}

Here are my four tests. the first three 'it' blocks pass successfully, the fourth is where I am stuck, I have added comments in that "it" block:

    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();
});

回答1:


The first respond parameter is status, it should be

  $httpBackend.when('POST', 'https://wwws.mint.com/overview.event').respond(401);

It is always good to use Sinon/Jasmine spies/stubs instead of noops in stubbed methods, so their calls could be tested:

var sandbox;

beforeEach(() => {
  sandbox = sinon.sandbox.create();
});

afterEach(() => {
  sandbox.restore();
});

beforeEach(angular.mock.module(($httpProvider, $provide) => {
  $httpProvider.interceptors.push(AuthInterceptor);
  $provide.factory('AuthService', () => ({
    jwtToken: "hello",
    backtoAuth: sandbox.stub();
  }));
}));


来源:https://stackoverflow.com/questions/38985850/angular-js-karma-chai-mock-an-authorization-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!