如何在Promise then()业力和茉莉花中对测试条件进行单位化

时间:2019-01-03 14:39:59

标签: angularjs unit-testing karma-jasmine

我正在将AngularJS 1.7与Karma和Jasmine一起使用。我已经开始学习单元测试用例。

我的控制器下面有一个示例方法

_this.method = function () {
    Service.getData().then(function (response) {
        if (response.productId === "ClientAPI") {
            // Some code
        }
        else {
            // Some Code
        }
    }, function (error) {
        _this.inProgress = false;
        if (error.status === 400) {
            // Some Code
        } else {
            // Some Code
        }
    })
}

下面是我的测试用例:

describe('Some Route :: Controller => ', function () {
    var $componentController;
    var Service;

    beforeEach(module('app'));
    beforeEach(inject(function (_$componentController_, _Service_) {
        Service = _Service_;
        spyOn(Service, 'getData').and.callFake(function() {
            var deferred = $q.defer();
            var response = {};
            response.productId = "ClientAPI";
            deferred.resolve(result);
            return deferred.promise;
        });
        ctrl = $componentController('controllerName', { Service: Service });
    }));

    it('Ctrl Method : should true', function () {
        ctrl.method();

        expect(Service.getData).toHaveBeenCalled();

        Service.getData().then(function (response) {
            expect(response.productId).toBe("ClientAPI")
        })

    });
});

但对于这种情况if (response.productId === "ClientAPI") {

,我的分支覆盖范围未显示

不确定在诺言中测试时我做错了什么。

1 个答案:

答案 0 :(得分:1)

您需要调用$ scope。$ apply()来触发对promise回调的调用:

beforeEach(inject(function (_$componentController_, _Service_) {
    Service = _Service_;
    spyOn(Service, 'getData').and.returnValue($q.resolve({ productId: 'ClientAPI' }));
    ctrl = $componentController('controllerName', { Service: Service });
}));

it('Ctrl Method : should true', inject(function($rootScope) {
    ctrl.method();

    expect(Service.getData).toHaveBeenCalled();
    $rootScope.$apply();

    // now test that the ctrl state has been changed as expected.
    // testing that the service has returned ClientAPI is completely useless:
    // the service is a mock, and you have told the mock to return that
    // this should test the component, based on what you've told the service
    // to return. It's not supposed to test the mock service.
    // testing what the service returns tests jasmine, not your code.
});