【问题标题】:How to provide injected values while unit testing a component in angular5+如何在 angular5+ 中对组件进行单元测试时提供注入值
【发布时间】:2019-01-17 16:33:02
【问题描述】:

我正在为一个动态初始化为模态(entryComponent)的组件编写测试。该组件的输入通过注入器检索。 我需要一种方法在 beforeEach 的组件创建步骤中提供这些输入。

this.modalService.create({
    component: sampleComponent, inputs: {
        test: 'testMsg'
    }
});

示例组件:

@Modal()
@Component({
    selector: 'sample-component',
    templateUrl: './sample.component.html',
    styleUrls: ['./sample.component.scss']
})
export class SampleComponent implements OnInit {
    test: string;

    constructor(private injector: Injector) {
    }

    ngOnInit() {
        this.test= this.injector.get('test');
    }
}

对 sampleComponent 的测试:

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

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [SampleComponent],
            imports: [
                ModalModule,
                BrowserAnimationsModule,
            ],
            providers: [
                ModalService,
            ]
        })
        .compileComponents();
        })
    );
    beforeEach(() => {
        fixture = TestBed.createComponent(SampleComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        component.ngOnInit();
    });
    it('should create', () => {
        expect(component).toBeTruthy();
    });
});

测试失败: 错误:StaticInjectorError(DynamicTestModule)[测试]: StaticInjectorError(平台:核心)[测试]: NullInjectorError: 没有提供者进行测试!

在这种情况下如何为“测试”提供价值?

【问题讨论】:

    标签: javascript unit-testing angular5


    【解决方案1】:

    在提供者中,为组件期望的注入值提供值:

    providers: [
        { provide: 'test', useValue: 'valueOfTest' }
    ]
    

    【讨论】:

      猜你喜欢
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      • 2019-03-01
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      相关资源
      最近更新 更多