gpt4 book ai didi

javascript - 测试 Angular 1.5 组件 $componentController 未定义

转载 作者:行者123 更新时间:2023-11-29 23:41:35 25 4
gpt4 key购买 nike

我正在关注 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 ...

最佳答案

首先,您需要将您的组件名称从“MyComponent”更改为“myComponent”,组件名称需要以小写字母开头。
我通过在注入(inject)中获取 Controller 稍微改变了测试:

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);
});
});

他们都通过了。

关于javascript - 测试 Angular 1.5 组件 $componentController 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45111369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com