Jasmine Angular测试指令应该失败

时间:2018-04-20 08:42:02

标签: javascript angular jasmine angular-directive

所以我做了一个简单的指令,当输入无效时抛出错误,但是当我试图期望抛出它成功时,这是正确的,但是当我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();
        }
    }
}

1 个答案:

答案 0 :(得分:5)

toThrow期望函数作为参数。

将您的断言更改为此

expect(
  () => fixture.detectChanges()
.toThrow()