所以我做了一个简单的指令,当输入无效时抛出错误,但是当我试图期望抛出它成功时,这是正确的,但是当我not.toThrow()
它成功时。这告诉我,我做错了什么,但无法弄清楚是什么。有人可以帮忙吗?
// Test component
@Component({
template: `<div [addClass]="data"></div> `
})
class TestAddClassComponent {
data: string | Array<string>;
}
describe('AddClassDirective', () => {
let component: TestAddClassComponent;
let fixture: ComponentFixture<TestAddClassComponent>;
let element: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestAddClassComponent, AddClassDirective]
});
fixture = TestBed.createComponent(TestAddClassComponent);
component = fixture.componentInstance;
element = fixture.debugElement.query(By.css('div'));
});
it('should throw error', () => {
component.data = 'some-invalid-input';
fixture.detectChanges();
expect(component).toThrow();
// Same result as:
// expect(component).not.toThrow();
});
});
@Directive({
selector: '[addClass]'
})
export class AddClassDirective implements OnInit {
ngOnInit() {
if (this.valid(this.value)) {
// Do something
} else {
throw new Error();
}
}
}
答案 0 :(得分:5)
toThrow
期望函数作为参数。
将您的断言更改为此
expect(
() => fixture.detectChanges()
.toThrow()