测试Angular 1.5组件$ componentController未定义

时间:2017-07-14 20:46:51

标签: javascript angularjs jasmine

我跟随documentation for testing Angular 1.5 components

我收到错误,其中$ componentController未定义。我确信它很简单,但我不知道这里有什么问题。

这是我的测试组件。

class MyComponent {
  constructor() {
    this.counter = 0;
  }
  $onChanges() {}
  $onDestroy() {}
  addToCounter() {
    this.counter += 1;
  }
}

MyComponent.$inject = [];

angular.module( 'my.component', [] )
  .component( 'MyComponent', {
      controller: MyComponent,
      bindings: {},
      template: `
        <div>Hello World</div>
      `,
} );

这是测试

describe( 'module: my.component', function() {

    var $componentController;

    beforeEach( module( 'my.component' ) );

    beforeEach( inject( function( _$componentController_ ) {
        $componentController = _$componentController_;
    } ) );

    it( 'should default counter to 0', function() {
        var bindings = {};
        console.log( '$componentController', $componentController );
        var ctrl = $componentController( 'MyComponent', null, bindings );
        expect( ctrl.counter )
            .toEqual( 0 );
    } );
} );

这是Jasmine正在输出的内容

LOG: '$componentController', undefined
...
TypeError: undefined is not a constructor (evaluating '$componentController( 'MyComponent', null, bindings )') in ...

2 个答案:

答案 0 :(得分:1)

首先,您需要将组件名称从“MyComponent”更改为“myComponent”,组件名称需要以小写字母开头。
我通过在inject:

中获取控制器来稍微改变了测试
let controller;
beforeEach(() => {
   angular.mock.module( 'my.component' );
   inject(($componentController) => {
    controller = $componentController("myComponent");
   });
});

这样做之后,我运行了这3个测试:

describe("Just some test", () => {
  it("should fetch controller", () => {
    expect(controller).toBeDefined();
  });
  it("counter should be 0", () => {
    expect(controller.counter).toBe(0);
  });
  it("should increase counter value to 1", () => {
    controller.addToCounter();
    expect(controller.counter).toBe(1);
  });
});

他们都过去了。

答案 1 :(得分:0)

尝试MyComponent而不是my.componenet