Property 'value' does not exist on type 'HTMLElement' in React Testing Library
Asked Answered
P

4

18

I am using React-testing-library and getting an error on the last line which is: expect (title.value).toBe("testtitle");})}) . The error message is Property 'value' does not exist on type 'HTMLElement'. How can I rectify this error message in order to write this code efficiently?

Testfile

  <Router history={history}>
            <Route render={(props) => 
            <NewQuestion {...props} onSave={jest.fn()}/>}/>
        </Router>)
    const title= getByPlaceholderText("What's your question? Be specific");
    fireEvent.change(title, {target: {value: "testtitle"}})
    expect (title.value).toBe("testtitle");})})
Precedency answered 30/1, 2020 at 13:10 Comment(0)
A
44

You should cast the title variable to HTMLInputElement to actually be able to have the value property. Try the following code:

const title = getByPlaceholderText("test") as HTMLInputElement;
Antimicrobial answered 30/1, 2020 at 13:21 Comment(0)
M
6

In my case,

  expect(
    screen.getByLabelText(/barInput/).value,
  ).toEqual('bar value');

throw Error "Property 'value' does not exist on type 'HTMLElement'."

I solved it by just adding generics HTMLInputElement

  expect(
    screen.getByLabelText<HTMLInputElement>(/barInput/).value,
  ).toEqual('bar value');
Malnourished answered 21/1, 2022 at 0:3 Comment(0)
C
1

An alternative to casting is to use instanceof narrowing:

const title = getByPlaceholderText("test");
if (!(title instanceof HTMLInputElement)) {
  throw new AssertionError("expected title to be an HTMLInputElement");
}
// Now TypeScript knows title is an HTMLInputElement if we made it here.
expect(title.value).toBe("foo");

This is more code than casting but arguably a better test because we'll get an explicit failure if the element returned is not an HTMLInputElement. This approach is inspired by this dom-testing-library github issue comment.

If you have to do this type of check in multiple spots, you can make an assertion function for reuse:

function assertIsHTMLInputElement(
  val: unknown
): asserts val is HTMLInputElement {
  if (!(val instanceof HTMLInputElement)) {
    throw new AssertionError(`expected ${val} to be an HTMLInputElement`);
  }
}
Claudiaclaudian answered 29/9, 2021 at 15:21 Comment(0)
M
0

I had a similar problem but just with href.

I used HTMLAnchorElement to solve the error:

const button = screen.getByRole<HTMLAnchorElement>('button');
expect(button.href).toContain('/something/awesome');
Micrococcus answered 17/1, 2023 at 16:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.