javascript - Jasmine Angular 测试指令应该失败

标签 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();
        }
    }
}

最佳答案

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

将你的断言改成这样

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

关于javascript - Jasmine Angular 测试指令应该失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49937553/

相关文章:

javascript - 保存 jasmine Expect() 结果

javascript - 为什么这个 Jasmine 测试在 Firefox 中偶尔会失败

javascript - Ajax 上的 POST 请求完成

angular - NgRx/Effects 不触发 Reducer

javascript - 使用事件发射器时无法运行我的 Angular 2 应用程序

angular - 从 Angular 5 更新到 6 后,我不断收到错误 : can't resolve timers in xml2js

javascript - 如何使用 quasar VueJS 制作 react slider

javascript - 在 arcgis javascript 中手动为图形图层添加图例

javascript - "Cannot read property ' setState ' of undefined"即使它是绑定(bind)的

javascript - Jasmine 的 beforeEach 是同步的吗?