jeudi 24 septembre 2020

React testing: Change select value in test

I am trying to write a test to check a value after a change in a <select> dropdown. This is my component:

import React from 'react';

const BasicDropdown = ({ key, value, options }) => {
  return (
    <div className={`basic-dropdown-${key}`}>
      <select
        className={`basic-dropdown-${key}-select`}
        name={`basic-dropdown-${key}-select`}
        {...{value}}
      >
        {options.map(option =>
          <option
            className={`basic-dropdown-${key}-select-${option}-option`}
            key={option}
            value={option}
          >
            {option.charAt(0).toUpperCase() + option.slice(1)}
          </option>
        )}
      </select>
    </div>
  );
};

export default BasicDropdown;

So far it's very simple. The reason for having a component is that I will expand this later depending on the props and other things. So I decided to write a test for this component to start with:

import React from 'react'
import TestUtils from 'react-dom/test-utils';
import BasicDropdown from './BasicDropdown';

const options = ['option-A', 'option-B', 'option-C'];

describe("BasicDropdown", () => {
  let renderedCmpt;

  beforeAll(() => {
    renderedCmpt = TestUtils.renderIntoDocument(
      <BasicDropdown key="test" value="option-A" options={options} />
    )
  });

  it("Should have correct value after change", () => {
    const select = TestUtils.findRenderedDOMComponentWithClass(renderedCmpt, 'basic-dropdown-test-select');
    expect(select.value).toEqual("option-A");
    TestUtils.Simulate.change(select, {target: {value: 'option-C'}});
    const selectChanged = TestUtils.findRenderedDOMComponentWithClass(renderedCmpt, 'basic-dropdown-test-select');
    expect(selectChanged.value).toEqual("option-C");
  });
});

My problem is that when running this test using jest (jest --coverage=false --config ~/projects/Beehive/config/jest.config.js ~/projects/Beehive/tests/BasicDropdown-test.js) I get the following error:

Expected: "option-C"
Received: "option-A"

at line 21, which means that the value of the select is never changed during the Simulate.

What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire