【问题标题】:Testing angular $http inside promise chain with mocha使用 mocha 在 Promise 链中测试 Angular $http
【发布时间】:2016-11-20 10:27:51
【问题描述】:

我为后端角度测试设置了 jsdom/mocha/chai。

我有一个基本上可以做到这一点的服务(故意没有发布数据):

app.service('testService', ['config', '$http', function(config, $http) {
    function getSpecificConfig(type) {
        return config.getConfig()
        .then(function(config) {
            // config is coming back defined;
            // $http timesout
            return $http({method: 'post', url: 'http://localhost:2222/some/path', withCredentials: true});
        })
        .then(function(res) {
            return res.data.config[type];
        })
        .catch(function(err) {
            //handles err
        });
    };

    return {
        getConfig: getConfig
    }
}]);

我的测试是:

/* jshint node: true */
/* jshint esversion: 6 */

let helpers = require(bootstrapTest),
    inject = helpers.inject,
    config,
    specificConfig,
    mockResponse,
    $httpBackend,
    $rootScope;

//config service
require('config.js');

//testService I'm testing
require('testService');

beforeEach(inject(function($injector, _$httpBackend_) {
    config = $injector.get('config');
    specificConfig = $injector.get('testService');
    $rootScope = $injector.get('$rootScope');
    $httpBackend = _$httpBackend_;

    $httpBackend.when('POST', 'http://localhost:2222/some/path')
    .response(function(data) {
        //would like this to fire
        console.log('something happened');
        mockResponse = {data: 'some data'};
        return mockResponse;
    });
}));   

afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectations();
    $httpBackend.verifyNoOutstandingRequest();
});

describe ('this service', function() {
    beforeEach(function() {
        $httpBackend.expect('POST', 'http://localhost:2222/some/path');
        $rootScope.$apply(function() {
            return specificConfig('something');
        });
    });

    it ('returns the specific config', function() {
        expect(mockResponse).to.equal('some data');
    })
});

问题: 运行测试时,config.getConfig() 正确解析,但 $http 导致 mocha 超时(2000 毫秒)并且 afterEach 钩子抛出 Unsatisfied 请求。

我对此的理解可能完全不正确,因此请随时教育我正确的方法(这是我的方法):

1) 需要所有必要的依赖项。

2) 注入它们并设置一个 $httpBackend 侦听器,该侦听器会在触发真正的 http 时触发测试响应。

3) $rootScope.$apply() 任何承诺,因为它们的解决方案与角度生命周期相关。

4) 每个设置监听器之前的第一个,每个触发服务之前的第二个,该服务触发 $http 允许 $httpBackend 触发并设置 mockResponse。

5) 测试模拟响应。

【问题讨论】:

标签: javascript angularjs mocha.js chai httpbackend


【解决方案1】:

如果您需要在模拟的 HTTP 请求中返回 Promise,您可以使用 angular-mocks-async,如下所示:

var app = ng.module( 'mockApp', [
    'ngMockE2E',
    'ngMockE2EAsync'
]);

app.run( [ '$httpBackend', '$q', function( $httpBackend, $q ) {

    $httpBackend.whenAsync(
        'GET',
        new RegExp( 'http://api.example.com/user/.+$' )
    ).respond( function( method, url, data, config ) {

        var re = /.*\/user\/(\w+)/;
        var userId = parseInt(url.replace(re, '$1'), 10);

        var response = $q.defer();

        setTimeout( function() {

            var data = {
                userId: userId
            };
            response.resolve( [ 200, "mock response", data ] );

        }, 1000 );

        return response.promise;

    });

}]);

【讨论】:

    猜你喜欢
    • 2015-02-17
    • 2017-04-08
    • 2013-02-10
    • 2021-07-24
    • 2016-05-26
    • 2019-02-04
    • 2015-07-16
    • 2015-12-01
    • 2017-02-04
    相关资源
    最近更新 更多