angular js karma/chai-模拟授权错误 [英] angular js karma/chai - mock an authorization error

查看:95
本文介绍了angular js karma/chai-模拟授权错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是TDD的新手,正在用angular js测试authInterceptor(我可以使用chai/mocha/sinon),它具有两个功能,一个请求和一个ResponseError.我已经成功测试了request函数,但是我不知道如何(搜索文档)模拟401(未经授权)错误.这是拦截器:

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

}

这是我的四个测试.前三个"it"块成功通过,第四个是我遇到的问题,在该"it"块中添加了注释:

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

推荐答案

第一个respond参数是status,应该是

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

最好使用Sinon/Jasmine间谍/存根而不是存根方法中的noop,这样可以测试它们的调用:

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

这篇关于angular js karma/chai-模拟授权错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆