Angular-使用ng5-slider进行单元测试

时间:2019-10-30 18:05:38

标签: angular unit-testing karma-jasmine

我有一个使用ng5-slider的组件。

    form: FormGroup;
    cities = [];
    hddTypes = [];
    minValue = 0;
    maxValue = 72000;
    options: Options = {
        floor: 0,
        ceil: 72000,
        translate: (value: number, label: LabelType): string => {
            switch (label) {
                case LabelType.Low:
                    return `<b>Min:</b> ${value} GB`;
                case LabelType.High:
                    return `<b>Max:</b> ${value} GB`;
                default:
                    return `${value} GB`;
            }
        },
        step: 1000,
        showTicks: true
    };
    .
    .
    . 

我为此组件创建了一个单元测试,但是出现了这个错误:

失败:模板解析错误: 无法绑定到“值”,因为它不是“ ng5-slider”的已知属性。

在测试中添加ng-5 slider的最佳实践是什么?

这是我的考试:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, FormBuilder } from '@angular/forms';
import { CommonModule } from '@angular/common';
import {SearchComponent} from './search.component';

describe('StaticComponent', () => {
    let component: SearchComponent;
    let fixture: ComponentFixture<SearchComponent>;
    const formBuilder: FormBuilder = new FormBuilder();
    beforeEach(
        async(() => {
            TestBed.configureTestingModule({
                declarations: [
                    SearchComponent,
                ],
                imports: [
                    CommonModule,
                    ReactiveFormsModule
                ],
                providers: [
                    // reference the new instance of formBuilder from above
                    { provide: FormBuilder, useValue: formBuilder }
                ]
            }).compileComponents();
        })
    );

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

        // pass in the form dynamically
        component.form = formBuilder.group({
            location: null,
            type: null,
            ram: null,
            storage: null,
        });
        fixture.detectChanges();
    });

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


  [1]: https://i.stack.imgur.com/WzbHu.png

1 个答案:

答案 0 :(得分:1)

如Angular的documentation中所述,一种方法是提供存根组件。

单元测试的目的是通过模拟任何外部依赖项来将组件作为一个单元进行测试。因此,您应该只为子组件接口而烦恼,而不是实现细节。

在describe块之前,创建一个存根组件:

@Component({selector: 'ng5-slider', template: ''})
class NgSliderStubComponent {
    @Input() value;
}

然后,在configureTestingModule中,在声明数组中添加NgSliderStubComponent。

declarations: [SearchComponent, NgSliderStubComponent],