简体   繁体   English

如何使用@testing-library/react 和 react-test-renderer 测试由 Redux 状态控制的输入值?

[英]how to test input value controlled by Redux state using @testing-library/react and react-test-renderer?

Using @testing-library/react,I am trying to test whether the input value is being by fireEvent or not.使用@testing-library/react,我试图测试输入值是否由fireEvent 产生。 But Facing a problem, its always returning blank.As the value is controlled by the redux store.但是遇到问题,总是返回空白,因为值是由redux store控制的。

Here is the code:这是代码:

<div ref={typeAheadRef} className={`dropdown${isOpen ? ' show' : ''}`} data-testid="searchContent">
            <InputGroup>
              <InputGroup.Prepend>
                <InputGroup.Text>
                  <img className="icon" src={SearchIcon} alt="search-icon" />
                </InputGroup.Text>
              </InputGroup.Prepend>
              <FormControl
                data-testid="search-input"
                ref={typeAheadInputRef}
                onInput={typeAheadInputHandler}
                onBlur={handleBlurEvent}
                value={props.searchValue}
                type="text"
                as="input"
                id="search-input"
                autoFocus
                autoComplete="off"
              />
            </InputGroup>
            {clearButton && (
              <Button
                data-testid="Close"
                type="button"
                className="close"
                aria-label="Close"
                onClick={handleClearSearch}
              >
                <span aria-hidden="true">&times;</span>
              </Button>
            )}
</div> 

This is the change Method(i'm using OnInput attribute for onChange and copy paste functionality)这是更改方法(我将 OnInput 属性用于 onChange 和复制粘贴功能)

const typeAheadInputHandler = event => {
    typeAheadInputRef.current.value = event.target.value;
    if (typeAheadInputRef.current.value !== '' &&
      typeAheadInputRef.current.value.length > 0) {
      setClearButton(true);
    } else {
      setClearButton(false);
    }

    props.handleTypeAheadOnSearch(typeAheadInputRef.current.value.trimStart());// method in parent component that sets search value

Parent component function:父组件函数:

const handleTypeAheadOnSearch = (query) => {
  props.setSearchValue(query); //updates the store value
}

Test.js测试.js

import '@testing-library/jest-dom/extend-expect';
import React from 'react';
import { render, fireEvent, getByTestId } from '@testing-library/react';
import ShallowRenderer from 'react-test-renderer/shallow';
import { DEFAULT_LOCALE } from '../../../i18n';
import { createStore } from 'redux';
import { Provider } from 'react-redux';

import SearchBar from '../index';
import StudentData from './data/StudentData';
import {
    getTypeAheadSearchStudentList,
    setSearchValue,
    setSearchValueEmpty,
    filterOutSearchStudents,
    openSearchDisplay,
    closeSearchDisplay,
} from '../../../containers/App/actions';
import { debug } from 'util';

const { IntlProvider } = jest.requireActual('react-intl');

const renderer = new ShallowRenderer();

const searchSetUp = () => {
    const handleTypeAheadOnSearch = jest.fn();
    const handleTypeAheadOnSelected = jest.fn();
    const handleSearchSubmit = jest.fn();
    const handleClearSubmit = jest.fn();

    const { container } = render(
        <SearchBar
            {...StudentData}
            handleTypeAheadOnSearch={handleTypeAheadOnSearch}
            handleTypeAheadOnSelected={handleTypeAheadOnSelected}
            handleSearchSubmit={handleSearchSubmit}
            handleClearSubmit={handleClearSubmit}
            showCourseValue={StudentData.showCourseSearchValue}
            setSearchValueEmpty={() => {
                setSearchValueEmpty();
            }}
        />,
    );
    return container;
};

describe('<Search>', () => {

    it('Should render and match the snapshot', () => {
        renderer.render(<SearchBar />);
        const renderedOutput = renderer.getRenderOutput();
        expect(renderedOutput).toMatchSnapshot();
    });

    it('renders Search component correctly', () => {
        const handleTypeAheadOnSearch = jest.fn();
        const handleTypeAheadOnSelected = jest.fn();
        const handleSearchSubmit = jest.fn();
        const handleClearSubmit = jest.fn();

        render(
        <IntlProvider locale={DEFAULT_LOCALE}>
            <SearchBar
                {...StudentData}
                handleTypeAheadOnSearch={handleTypeAheadOnSearch}
                handleTypeAheadOnSelected={handleTypeAheadOnSelected}
                handleSearchSubmit={handleSearchSubmit}
                handleClearSubmit={handleClearSubmit}
                showCourseValue={StudentData.showCourseSearchValue}
                setSearchValueEmpty={() => {
                    setSearchValueEmpty();
                }}
            />
        </IntlProvider>
        );
    });

    it('should render the search component', () => {
        const container = searchSetUp();
        const searchIcon = getByTestId(container, 'searchIcon');
        expect(searchIcon.textContent).toBe('');
    });

    it('Search icon is clicked and shows the text box', () => {
        const container = searchSetUp();
        const searchIcon = getByTestId(container, 'searchIcon');
        fireEvent.click(searchIcon);
        const searchContent = getByTestId(container, 'searchContent');
        expect(searchContent.textContent).toBe('No matching students found.');
    });

    it('Show Close icon on type', () => {
        const container = searchSetUp();
        const searchIcon = getByTestId(container, 'searchIcon');
        fireEvent.click(searchIcon);
        const input = getByTestId(container, 'search-input');
        fireEvent.change(input, { target: { value: 'stu' } });
        expect(input.value).toBe('stu');
        console.log(input.value);// blank 
    });
});

Really Need help on this.真的需要这方面的帮助。

What you can do is make your own small store for your test.您可以做的是为您的测试制作自己的小商店。 You just need to :你只需要:

  • import your reducer导入你的减速器
  • const store = createStore(myReducer)
  • put a <Provider store={store}> on you tested component在你测试的组件上放一个<Provider store={store}>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM