gpt4 book ai didi

Angular Testing : provide injected @Attribute in TestBed

转载 作者:行者123 更新时间:2023-11-28 20:36:57 26 4
gpt4 key购买 nike

我有一个通过@Attribute 获取属性注入(inject)的组件:

@Component({
selector: 'app-foo',
templateUrl: './foo.component.html'
})
export class FooComponent implements OnInit {

constructor(@Attribute('foo') private foo: string) {
// do something with foo
}
}

现在我想使用 Jasmine 和 Karma 编写一个测试。不幸的是,我找不到任何关于如何通过 TestBed 注入(inject)器在测试中提供此属性的文档。

这是我尝试过的:

describe('FooComponent', () => {

beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
{provide: 'foo', useValue: 'bar'},
{provide: Attribute('foo'), useValue: 'bar'},
],
declarations: [FooComponent],
})
.compileComponents();
}));

it('should merge outer class', () => {
const fixture = TestBed.createComponent(FooComponent);
const component = fixture.componentInstance;
fixture.detectChanges();

// do actual testing
});
});

经过一些研究,我还定义了以下但没有成功:

Inject('foo')(FooComponent, null, 0);
Attribute('foo')(FooComponent, null, 0);

传递给构造函数的参数总是null。有人知道解决方案吗?我正在使用 Angular 5.2.10。

最佳答案

还努力提供一个 @Attribute() 装饰器覆盖。

作为解决方法,您可以将构造函数中的 @Attribute() 更改为组件类中的 @Input() foo: string;。或者使用包装器组件,并在包装​​器组件上设置属性,如下所示:

import { TestBed } from "@angular/core/testing";
import { Attribute, Component } from "@angular/core";
import { By } from "@angular/platform-browser";

describe('FooComponent', () => {
it('should allow you to use attribute decorator', () => {
TestBed.configureTestingModule({
declarations: [FooComponent, WrapperComponent],
});

const wrapperFixture = TestBed.createComponent(WrapperComponent);
wrapperFixture.detectChanges();

const fooComponent = wrapperFixture.debugElement.query(By.directive(FooComponent)).componentInstance;
expect(fooComponent.bar).toEqual('baz');
});
});

@Component({
selector: "foo-component",
template: "<p>Foo works: {{bar}}</p>",
})
class FooComponent {
bar: '';
constructor(@Attribute('foo') private foo: string) {
this.bar = foo;
}
}

@Component({
selector: "wrapper-component",
template: "<foo-component foo='baz'></foo-component>"
})
class WrapperComponent {
}

我认为在组件上使用 @Input() 对我来说会更好。到目前为止,我看不出有任何缺点。

关于 Angular Testing : provide injected @Attribute in TestBed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50817811/

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