Angular 2/4 – 如何测试指令@Input值?

前端之家收集整理的这篇文章主要介绍了Angular 2/4 – 如何测试指令@Input值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我有一个指令,需要输入:

@Directive({
    selector: '[my-directive]'
})
export class MyDirective {

    @Input('some-input')
    public someInput: string;
}

如您所见,输入应为字符串值.现在,我想为这个指令编写测试,我想测试输入是否满足字符串类型:

describe('MyDirective',() => {

    let fixture: ComponentFixture<DummyComponent>;
    let dummy: DummyComponent;
    let directive: DebugElement;

    beforeEach(async(() => {

        TestBed
            .configureTestingModule({
                imports: [
                    MyModule.forRoot()
                ],declarations: [
                    DummyComponent
                ]
            })
            .compileComponents();

        fixture = TestBed.createComponent(DummyComponent);
        dummy = fixture.componentInstance;
        directive = fixture.debugElement.query(By.directive(MyDirective));

        fixture.detectChanges();
    }));

    it('should satisfy only a string input and error on other inputs',() => {
        // How to test?
    });
});

@Component({
    selector: 'dummy',template: `
        <div my-directive [some-input]="'just-a-string-value'"></div>
    `
})
export class DummyComponent implements OnInit {
}

如何测试@Input值是否属于正确类型?

解决方法

所以有点晚了,但我来到这里寻找同样的问题,所以我会发布我的解决方案.这是我测试指令输入(或其他属性)值所做的:

describe('MyDirective',() => {
        
        // needed so template is processed,inputs are updated
        fixture.detectChanges();
        
        // since we declared a ViewChild on the directive,we can access
        // and test directive properties values
        expect(component.directive.someInput).toEqual('just-a-string-value');
        // to test the input type :
        expect(component.directive.someInput).toEqual(Jasmine.any(String));
        // I thought TypeScript would complain when providing a wrong type input to a directive,but no...so I guess I'll test the input type too !
    });
});

@Component({
    selector: 'dummy',template: `
        <div my-directive [some-input]="'just-a-string-value'"></div>
    `
})
export class DummyComponent implements OnInit {

  // add a reference to the directive in template
  // so in your component you can access : this.directive,this.directive.someInput
  ViewChild(MyDirective) directive: MyDirective;
}

因此:修改测试组件以在指令实例上保存引用,然后通过component.directive.[property-name]访问指令属性.顺便提一下,如果为指令属性提供默认值(可以通过在模板中提供值来覆盖),则可以在调用fixture.detectChanges()之前测试它们.

猜你在找的Angularjs相关文章