Search code examples
react-testing-libraryjsdom

React Testing Library vs JsDom


I'm currently writing a test that checks for a simple input component:

it("Renders TextInput Component with correct display value", ()=>{
  const textInput = screen.getByRole("textbox");
})

If I wanted to check the value of the text input, should I be checking the attribute or using RTL's screen method (is there a preferred way of doing this?)

  expect(screen.getByDisplayValue(defaultProps.value));
  expect(textInput).toHaveAttribute('name', defaultProps.name);

I would like to start using more of RTL but I'm finding some attributes I pass down are harder to check like the ones below.

expect(textInput).toHaveAttribute('placeholder', defaultProps.label);
expect(textInput).toHaveAttribute('type',  defaultProps.type);

Solution

  • Yep, screen is the preferred way for sure. Read this article for more info on that and more tips.

    On your question about how to check the value of an input fields, you can do it like this:

    it("Renders TextInput Component with correct display value", ()=>{
      expect(screen.getByDisplayValue('my text')).toBeInTheDocument().
    })
    

    This will attempt to find an input with a value of "my text", just like a real user would. If it does find it then it's deemed a pass.