Jest-dom: add .toHaveValue matcher

Created on 4 Mar 2019  路  6Comments  路  Source: testing-library/jest-dom

The problem

65 implemented a high-level API for asserting values of an entire form, which is great. However, this API it does not allow to assert the value of a single form element, which is more desired is some scenarios

Describe the feature you'd like:

Add toHaveValue matcher (as described in the initial comment in #60) which can be used to assert value of a single form element - an input, select or textarea

expect(getByLabelText('Username')).toHaveValue('janedoe');

Suggested implementation:

Create toHaveValue(formElement, expectedValues) that calls existing getSingleElementValue (https://github.com/gnapse/jest-dom/blob/master/src/to-have-form-values.js#L38)

I will be glad to help with implementing this feature

Most helpful comment

Yeah, this works of course. However, there are scenarios when expect(element).toHaveValue(value) may be preferred:

  1. When I already have a reference to my field element:
const {getByLabel} = render(<Form/>);
const usernameInput = getByLabel('username');
expect(usernameInput).toBeEnabled();
expect(usernameInput).toHaveFocus();
expect(usernameInput).toHaveValue('some_value');
  1. When I don't care (or don't know) what name attribute my field has. I can treat it as an implementation details and reference the field by label or placeholder, just as users do. This fits well into philosophy of react-testing-library, and https://testing-library.com/docs/guiding-principles especially

All 6 comments

Hmmmm, and what about this?

toHaveFormValues({ username: 'janedoe' })`

Though I would not be opposed to add this extra matcher too. That was actually my first idea for this functionality, but then we realized that by providing the more generic one, users could make the simpler case work too, as depicted above.

Yeah, this works of course. However, there are scenarios when expect(element).toHaveValue(value) may be preferred:

  1. When I already have a reference to my field element:
const {getByLabel} = render(<Form/>);
const usernameInput = getByLabel('username');
expect(usernameInput).toBeEnabled();
expect(usernameInput).toHaveFocus();
expect(usernameInput).toHaveValue('some_value');
  1. When I don't care (or don't know) what name attribute my field has. I can treat it as an implementation details and reference the field by label or placeholder, just as users do. This fits well into philosophy of react-testing-library, and https://testing-library.com/docs/guiding-principles especially

I agree. This would be a great addition 馃憤

I definitely agree. Go for it. and thanks for your ideas and contributions!

Great! I will submit a PR soon

Closed in #90

Was this page helpful?
0 / 5 - 0 ratings