茉莉花角测试指令应该失败

e11*_*1en 3 javascript jasmine angular-directive angular

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

    });
});
Run Code Online (Sandbox Code Playgroud)

指示

@Directive({
  selector: '[addClass]'
})
export class AddClassDirective implements OnInit {

    ngOnInit() {
        if (this.valid(this.value)) {
          // Do something
        } else {
          throw new Error();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*ula 5

toThrow 需要一个函数作为参数。

将您的断言更改为此

expect(
  () => fixture.detectChanges()
.toThrow()
Run Code Online (Sandbox Code Playgroud)