所以我有一个输入的指令:
@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
值是否属于正确类型?
答案 0 :(得分:3)
所以有点晚了,但是我来这里寻找同样的问题,所以我将发布解决方案。这是我测试指令输入(或其他属性)值的方法:
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;
}
答案 1 :(得分:-1)
https://angular.io/guide/testing#test-a-component-with-inputs-and-outputs
具有输入和输出的组件通常出现在视图中 主机组件的模板。主机使用属性绑定进行设置 input属性和事件绑定来监听由引发的事件 输出属性。
测试目标是验证此类绑定是否按预期工作。该 测试应设置输入值并监听输出事件。
代码示例在链接中。