【问题标题】:Unit Testing Angular 9 Component with @Host parameter can't resolve parameters带有@Host参数的单元测试Angular 9组件无法解析参数
【发布时间】:2020-08-10 13:50:31
【问题描述】:

这个规范给了我一个

“错误:无法解析 FooComponent 的所有参数:(?)。”

错误,我不明白为什么。对此的任何帮助将不胜感激。

foo.component.ts

import {Component, Host } from '@angular/core';
import {BarComponent} from './bar.component';

@Component({
    selector: 'foo',
    template: `<div>foo</div>`
})
export class FooComponent {
    constructor(@Host() private barComponent: BarComponent) {
        // do something with bar
    }
}

bar.comonent.ts

import {Component, Injectable} from '@angular/core';

@Component({
    selector: 'bar',
    template: `<div>bar<foo/></div>`
})
@Injectable()
export class BarComponent { }

foo.component.spec.ts

import {TestBed, async, ComponentFixture} from '@angular/core/testing';
import {FooComponent} from './foo.component';
import {BarComponent} from './bar.component';

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

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [
                FooComponent,
            ],
            providers: [
                BarComponent
            ],
        });
    }));

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

    it('should compile', () => {
        expect(component).toBeTruthy();
    });
});

【问题讨论】:

    标签: angular unit-testing testing


    【解决方案1】:

    也许 configureTestingModule 的 overrideComponent 方法会有所帮助:

      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [
            FooComponent,
          ]
        }).overrideComponent(FooComponent, {
          add: {
            providers: [
              { provide: BarComponent }
            ]
          }
        });
      }));
    

    【讨论】:

      猜你喜欢
      • 2018-01-07
      • 2017-11-13
      • 2016-11-18
      • 2017-02-11
      • 1970-01-01
      • 2018-06-12
      • 2017-11-20
      • 1970-01-01
      • 2017-04-24
      相关资源
      最近更新 更多