Nic*_*cky 7 testing unit-testing jasmine typescript angular
所以我有一个指令,需要输入:
@Directive({
selector: '[my-directive]'
})
export class MyDirective {
@Input('some-input')
public someInput: string;
}
Run Code Online (Sandbox Code Playgroud)
如您所见,输入应该是一个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 {
}
Run Code Online (Sandbox Code Playgroud)
如何测试@Input
值是否属于正确的类型?
So it's a bit late but I came here searching for the same problem, so I'll post my solution. Here is what I did to test a directive inputs (or other properties) values :
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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3932 次 |
最近记录: |