0
votes

I want to test a select change function,here is the code :

import React, { useEffect, useState } from 'react';
import Select from 'react-select';
function Component1(props) {
    const [content, setContent] = useState('initialized Value');
    const [color, setColor] = useState('initialized Value');

    const options = [
        { value: 'red', label: 'Red' },
        { value: 'green', label: 'Green' },
        { value: 'blue', label: 'Blue' },
    ];
    useEffect(async () => {
        fetchSomeData();
        // onclickButton();
    }, []);

    const fetchSomeData = async () => {
        console.log('fetchSomeData');
    };

    const onclickButton = () => {
        console.log('do something here onclickButton');
        setContent('updated Value');
    };

    const resetColor = (value) => {
        console.log(value);
        setColor(value);
    };

    return (
        <div data-testid='Component1'>
            Component1
            <button data-testid='button' onClick={onclickButton}>
                Button
            </button>
            <div>Button Test :{content}</div>
            <Select aria-label='select-Label' data-testid='select' options={options} value={color} onChange={resetColor} />
            <div data-testid='color-value'>Current Color:{color}</div>
        </div>
    );
}

I did some reasearches , and they said the best way is mocked a select and test it:

  beforeEach(() => {
        render(<Component1 />);
    });

    test('should 3', () => {
        jest.doMock('react-select', () => ({ options, value, onChange }) => {
            function handleChange(event) {
                const option = options.find((option) => option.value === event.currentTarget.value);
                onChange(option);
            }
            return (
                <select data-testid='custom-select' value={value} onChange={handleChange}>
                    {options.map(({ label, value }) => (
                        <option key={value} value={value}>
                            {label}
                        </option>
                    ))}
                </select>
            );
        });

        fireEvent.change(screen.getByTestId('select'), {
            target: { value: 'green' },
        });

    test('should 2', () => {
        // screen.debug()
        const onclickButton = jest.fn();
        // render(<Component1 onclickButton={onclickButton} />);

        fireEvent.click(screen.getByTestId('button'), {
            // target: { value: 'JavaScript' },
        });

    });

after I run the test, I got this :

TestingLibraryElementError: Unable to find an element by: [data-testid="select"]

can some one help me? I just want below codes can be covered by unit test enter image description here

update:

I tried to use queryByLabelText, and it works, but still ,it seems not trigger the onChange event. I got this: Expected element to have text content: Current Color:green Received: Current Color:red

fireEvent.select(screen.queryByLabelText('select-Label'),{target:{value:'green'}})

expect(screen.queryByTestId('color-value')).toHaveTextContent('Current Color:green');
1
It looks to me that getByTestId is not been imported. Would you confirm it?Jai
yes I can sure getByTestId has been imported ,case I have 2 test case,another one is also used getByTestId , and it has passed the testjjzjx118_2
@Jai I fount why -- I missing the screen bfore the getByTestId function. but still it gave an error says —— Unable to find an element by: [data-testid="select"]jjzjx118_2

1 Answers

1
votes

I resolved it by below code:

const DOWN_ARROW = { keyCode: 40 };
fireEvent.keyDown(screen.getByLabelText('select-Label'), DOWN_ARROW);
fireEvent.click(screen.getByText('Green'));     

these code will trigger onChange event.

also refter to: how to test react-select with react-testing-library