使用$ httpbackend模拟和打字稿进行单元测试

时间:2015-06-30 06:04:40

标签: angularjs unit-testing typescript mocha chai

我正在尝试对使用$http服务发出http请求的方法进行单元测试,但是$httpbackend模拟似乎没有拦截请求 - 我得到{{1}错误。

我的测试如下:

Error: No pending request to flush !

我得到的结果是

/// <reference path="../typings/tsd.d.ts" />
/// <reference path="../dist/ngJwtAuth.d.ts" />


var expect = chai.expect;

describe('Service tests', () => {

    var $httpBackend:ng.IHttpBackendService;
    var ngJwtAuthService:NgJwtAuth.NgJwtAuthService;

    beforeEach(()=>{

        module('ngJwtAuth');

        inject((_$httpBackend_, _ngJwtAuthService_) => {
            $httpBackend = _$httpBackend_;

            if (!ngJwtAuthService){ //dont rebind, so each test gets the singleton
                ngJwtAuthService = _ngJwtAuthService_; //register injected of service provider
            }
        })
    });

    afterEach(() => {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it('should be an injectable service', () => {

        return expect(ngJwtAuthService).to.be.an('object');
    });

    it('should retrieve a json web token', () => {

        var user = {
            email: 'joe.bloggs@example.com',
            password: 'password'
        };

        $httpBackend.expectGET('/api/auth/login', (headers) => {
            return headers['Authorization'] == 'Basic '+btoa(user.email+':'+user.password);
        });

        var promisedToken = ngJwtAuthService.authenticate(user.email, user.password);

        promisedToken.then((res) => {

            console.log('res', res);
        });

        $httpBackend.flush();

    });


});

我正在测试的违规方法是

Start:
  Service tests
    ✔ should be an injectable service
    ✖ should retrieve a json web token
    ✖ "after each" hook

Finished in 0.055 secs / 0.004 secs

SUMMARY:
✔ 1 tests completed
✖ 2 tests failed

FAILED TESTS:
  Service tests
    ✖ should retrieve a json web token
      Chrome 43.0.2357 (Mac OS X 10.10.3)
    Error: No pending request to flush !
        at Context.<anonymous> (base/test/tmp/test.js?7ade37b85a3e515024b3ce23ba6d9fc4c70ddcc2:104:22)

    ✖ "after each" hook
      Chrome 43.0.2357 (Mac OS X 10.10.3)
    Error: Unsatisfied requests: GET /api/auth/login
        at Context.<anonymous> (base/test/tmp/test.js?7ade37b85a3e515024b3ce23ba6d9fc4c70ddcc2:86:22)

整个项目可在https://github.com/spira/angular-jwt-auth

找到

1 个答案:

答案 0 :(得分:1)

好吧,经过一段时间的游戏,我把它搞定了。事实证明解决方案是确保$httpbackend没有为每个功能重新声明。这看起来像这样:

inject((_$httpBackend_, _ngJwtAuthService_) => {

    if (!ngJwtAuthService){ //dont rebind, so each test gets the singleton
        $httpBackend = _$httpBackend_;
        ngJwtAuthService = _ngJwtAuthService_; //register injected of service provider
    }
})

由于我希望每个测试使用相同的服务(服务是可变的),我必须在if块中包含$httpBackend = _$httpBackend_;行。