Search code examples
angular-spectator

How can I test if a html input type radio is checked


I have this HTML in my component.html:

<input type="radio" [checked]="selected" (change)="select()" />

How can I make a Spectator query and expect to test if this input element is checked or not?

I have tried with:

expect(spectator.query('input')).toHaveAttribute('checked');

But I get the error:

Error: Expected element to have attribute 'checked', but had 'undefined'

And I have tried with:

expect(spectator.query('input')).toBeChecked();

But then I get the error:

Error: Expected element to be checked

How can I test this simple HTML input element?

Thank you
Søren


Solution

  • expect(spectator.query('input')).toBeChecked(); is the correct usage.

    It looks like selected property is false due to which radio button is not selected and you are getting this error. Simple fix you binding in test (by setting selected to true) or update assertion to check if radio button is not selected:

    expect(spectator.query("input[type=radio]")).not.toBeChecked();
    

    Take a look at this stackblitz code sample where I have 2 bound radio buttons one selected and another not selected and I have tests for it.

    it("should be checked", () => {
      spectator = createComponent();
      expect(spectator.query("#r1[type=radio]")).not.toBeChecked();
    });
    
    it("should not be checked", () => {
      spectator = createComponent();
      expect(spectator.query("#r2[type=radio]")).toBeChecked();
    });
    

    Also, take a look at this guide to see available custom matchers.