加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 18:06:26 所属栏目:安全 来源:网络整理
导读:所以我有一个指令,需要输入: @Directive({ selector: '[my-directive]'})export class MyDirective { @Input('some-input') public someInput: string;} 如您所见,输入应为字符串值.现在,我想为这个指令编写测试,我想测试输入是否满足字符串类型: describe
所以我有一个指令,需要输入:

@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()之前测试它们.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读