如何进行单元测试。然后使用jamsine进行功能

时间:2016-10-19 09:09:20

标签: javascript angularjs unit-testing jasmine angular-promise

我写过一个发布某些服务数据的组件。 我无法覆盖单元测试中的功能。如何进入测试`然后'功能

angular.module('myapp')
       .component('performAnalysis', {
            templateUrl: 'analysis.component.html',
            controller: PerformAnalysisController,
            controllerAs: 'vm'
        });

function PerformAnalysisController(UnitySizerService, SizingService, MarshallDTO, CommonService) {
    let vm = this;

    vm.$onInit = $onInit;

    function $onInit() {
        let unitySizerDTO = MarshallDTO.generateDTO();
        let previousDTO = CommonService.getProperty('previousDTO');

        vm.dataChanged = JSON.stringify(unitySizerDTO) === JSON.stringify(previousDTO);

        /* Call Backend API only if DTO is changed */
        if (!vm.dataChanged) {
            /* Loader On */
            vm.activateLoader = true;

            SizingService.postSizingResults(unitySizerDTO).then(function (data) {

                UnitySizerService.resultSummary = data;
                /* New Data coming from Backend */
                vm.dataChanged = true;
                /* Loader Off */
                vm.activateLoader = false;
                CommonService.setProperty('previousDTO', unitySizerDTO);
                vm.unitySizerService = UnitySizerService;
            });
        }
        else {
            vm.unitySizerService = UnitySizerService;
        }
    }
}

这是我编写的测试文件,但是我无法覆盖此内的then函数:

describe('my Component', function () {

beforeEach(module('myApp'));

let vm;
let $rootScope;
let $componentController;
let UnitySizerService, SizingService;

beforeEach(inject(function (_$componentController_, _$rootScope_, _UnitySizerService_, _SizingService_) {
    $componentController = _$componentController_;
    $rootScope = _$rootScope_;
    UnitySizerService = _UnitySizerService_;
    SizingService = _SizingService_;

    vm = $componentController('performAnalysis');
}));

it('should be defined', function () {
    expect(vm).toBeDefined();

    expect(vm.$onInit).toBeDefined();

    expect(UnitySizerService).toBeDefined();

});

it('should show loader', function () {
    vm.$onInit();

    vm.dataChanged = false;

    expect(vm.activateLoader).toBeTruthy();
});

});

1 个答案:

答案 0 :(得分:1)

为了模仿茉莉花中的承诺.then,你可以做这样的事情

var deferred = $q.defer();   
var whatServiceReturns = "test";

// we are returning promise from service function 
SizingService.postSizingResults.and.returnValue({$promise:deferred.$promise}); 

// now let's call the original function
vm.$onInit();

// we will resolve our promise so that we can reach inside 'then'
// here, 'whatServiceReturns' resembles your 'data' parameter in 'then' function
deferred.resolve(whatServiceReturns);

$rootScope.$digest();

// here we can expect things like 'dataChanged' and 'activateLoader' if we see from your example
expect(...).toEqual(...);

您可以使用deferred.reject(someError);表示错误。

编辑:添加评论以详细说明代码