角度 2 / 4 - 如何测试指令@Input值?



所以我有一个接受输入的指令:

@Directive({
selector: '[my-directive]'
})
export class MyDirective {
@Input('some-input')
public someInput: string;
}

如您所见,输入应为string值。现在,我想为此指令编写一个测试,并且我想测试输入是否满足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', () => {
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', () => {

// 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 访问指令属性。[属性名称]。顺便说一下,如果您为指令属性提供了默认值(可以通过在模板中提供值来覆盖(,则可以在调用 fixture.detectChanges(( 之前测试它们。

最新更新