如何用茉莉花单元测试一个可观测量

时间:2017-08-13 09:16:51

标签: angular typescript jasmine

我已经为构造函数添加了一些代码,现在我的单元测试失败了。新代码从可观察的对象this.isFollowOnMode设置为true或false:

import { CustomerGroupService } from 'customerGroup.service';

class HeaderBarController {
    private isFollowOnMode: boolean;

    constructor(private customerGroupService: CustomerGroupService) {
        'ngInject';

        //new code that is causing test to fail:

        this.customerGroupService.isFollowOnMode$ // will be true or false
            .subscribe((isFollowOnMode) => {
                this.isFollowOnMode = isFollowOnMode;
            });
    }

    // other stuff
}

export default HeaderBarController;

我的单元测试中出现以下错误:

  

PhantomJS 2.1.1(Mac OS X 0.0.0)控制器:HeaderBarController应定义为FAILED   TypeError:undefined不是构造函数(评估' this.customerGroupService.isFollowOnMode $'

这是我失败的单元测试:

describe('Controller: HeaderBarController', function () {
    beforeEach(angular.mock.module(module.name));

    beforeEach(angular.mock.module(function ($provide) {
        $provide.service('customerGroupService', () => { });

    }));

    beforeEach(inject(function ($rootScope, $componentController) {
        this.$scope = $rootScope.$new();
        this.ctrl = $componentController('headerBar',
            {
                // locals
                $scope: this.$scope,
                $element: [{}],
                $attrs: [],
            },
            {
                // scope bindings
            }
        );
    }));

    it('should be defined', function () {
        expect(this.ctrl).toBeDefined();
    });

});

所以我似乎没有设置this.customerGroupService.isFollowOnMode$。它的默认值应为false。在单元测试中。我是单元测试的新手,所以任何帮助都会很棒。感谢。

1 个答案:

答案 0 :(得分:1)

问题不是特定于可观察对象,而是适用于一般的服务存根。

$provide.service('customerGroupService', () => {});

将导致服务没有预期的属性,使用箭头而不是构造函数也是错误的。

ngMock已经提供了一种模拟服务的方法:

let customerGroupServiceMock;

beforeEach(() => {
  customerGroupServiceMock = {
    isFollowOnMode$: Observable.of(true);
  };
  angular.mock.module({ customerGroupService: customerGroupServiceMock });
});

也可以直接将模拟服务注入控制器,而不是在注入器中定义它们:

    this.ctrl = $componentController('headerBar',
        {
            // locals
            customerGroupService: customerGroupServiceMock,
            $scope: this.$scope,
            $element: [{}],
            $attrs: [],
        },

这正是'本地人'的意思。

相关问题