【问题标题】:Jasmine Angular testing a directive should failJasmine Angular 测试指令应该失败
【发布时间】:2018-09-30 22:18:48
【问题描述】:

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

【问题讨论】:

    标签: javascript angular jasmine angular-directive


    【解决方案1】:

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

    把你的断言改成这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-12
      • 2017-12-25
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多