简体   繁体   中英

Jasmine Angular testing a directive should fail

So I've made a simple directive that throws an error when the input is invalid but when I try to expect a throw it succeeds, which is correct, but when I not.toThrow() it succeeds the same. Which tells me I'm doing something wrong, but can't figure out what. Could somebody help?

Test

// 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

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

    ngOnInit() {
        if (this.valid(this.value)) {
          // Do something
        } else {
          throw new Error();
        }
    }
}

toThrow expects a function as an argument.

Change your assertion to this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM