angular - 使用@input 对 Angular 组件进行单元测试

我有一个 Angular 组件,它有一个@input 属性并在 ngOnInit 上处理它。通常,当对 @input 进行单元测试时,我只是将其指定为 component.inputproperty=value 但在这种情况下我不能,因为它被用于 ngOnInit。我如何在 .spec.ts 文件中提供此输入值。我能想到的唯一选择是创建一个测试主机组件,但如果有更简单的方法,我真的不想走这条路。

最佳答案

做一个测试主机组件是一种方法,但我知道它可能工作量太大。

组件的 ngOnInitTestBed.createComponent(...) 之后的第一个 fixture.detectChanges() 上被调用。

因此,为了确保它被填充到 ngOnInit 中,将它设置在第一个 fixture.detectChanges() 之前。

例子:

fixture = TestBed.createComponent(BannerComponent);
component = fixture.componentInstance;
component.inputproperty = value; // set the value here
fixture.detectChanges(); // first fixture.detectChanges call after createComponent will call ngOnInit

我假设所有这些都在 beforeEach 中,如果您想要为 inputproperty 设置不同的值,您必须通过 describe 获得创意s 和 beforeEach

例如:

describe('BannerComponent', () => {
  let component: BannerComponent;
  let fixture: ComponentFixture<BannerComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({declarations: [BannerComponent]}).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BannerComponent);
    component = fixture.componentInstance;
  });

  it('should create', () => {
    expect(component).toBeDefined();
  });

  describe('inputproperty is blahBlah', () => {
   beforeEach(() => {
     component.inputproperty = 'blahBlah';
     fixture.detectChanges();
   });

   it('should do xyz if inputProperty is blahBlah', () => {
     // test when inputproperty is blahBlah
   });
  });

  describe('inputproperty is abc', () => {
   beforeEach(() => {
     component.inputproperty = 'abc';
     fixture.detectChanges();
   });

   it('should do xyz if inputProperty is abc', () => {
     // test when inputproperty is abc
   });
  });
});

https://stackoverflow.com/questions/63839249/

相关文章:

python - 如何将带有元组键的 python 字典转换为 pandas 多索引数据框?

python - 为什么在 Pi 的整数倍处 torch.sin() 和 numpy.sin() 的

javascript - 悬停时高效的 JS 事件监听器

python - 从数据框中删除列中以 "@"开头的单词

python - 如何在 Python 中订阅 NATS 主题并继续接收消息?

java - 阵列旋转 TLE(超出时间限制)

f# - 在 F# 中添加两个元组

amazon-web-services - 服务器端加密与客户端加密 - Amazon S3

scala - 如何在不分配给 val 的情况下使用隐式调用返回的函数

java - Hibernate: OneToOne: 同一类型的两个字段