在我的浅层测试中如何定义匹配路由器道具

时间:2019-07-15 23:58:28

标签: reactjs redux react-router jestjs enzyme

我正在尝试使用我的react应用程序进行开玩笑+酶的测试,但是在路由组件上出现了错误。我正在使用路由器v4。

我确实尝试对浅层组件使用MemoryRouter包装器,或者使用mount代替浅层组件。一切都不正常。

我的测试:

describe('Movie Page tests', () => {
    const wrapper =  shallow(<Movie />).toJSON()

    it('should call Movie snapshot correctly', () => {
        const tree = renderer
            .create(wrapper)
            .toJSON();
        expect(tree).toMatchSnapshot();
        });
})

完整组件:

export const Movie = ({
   match, 
   searchMovieAction,
   movies,
   totalResults,
   pending,
   error,
  }, props) => {
    const [ showModal, setShowModal ] = useState(false);

    //const { searchMovieAction } = useActions();
    const { values, handleInputChange } = useFormInput({
      searchValue: '', 
    });

    console.log('PROPES ------>', error,);

    /* const {
        movie: {
          movie,
          totalResults,
          pending,
          error,
        },
    } = useSelector(state => state); */

    const handleSubmit = (e) => {
      e.preventDefault()
      const { searchValue } = values;

      if(searchValue) {
        searchMovieAction(searchValue);
      }

    }

    const toggleModal = () => {
      setShowModal(!showModal);
    }

    return (
        <div className='movies'>
            <div>
              <StyledForm onSubmit={handleSubmit}>
                <DefaultInput 
                    name='searchValue' 
                    value={values.searchValue}
                    placeholder='Search a movie...'
                    handleChange={handleInputChange} 
                  />
                <Button solid rounded right >Search</Button>
              </StyledForm>
            </div>

            { pending && <LoadingSpinner medium />}

            { error && <Error message={error} /> }

            { movies && movies.length > 0 && !pending && !error && (
              <p>
                We found <strong>{ totalResults }</strong>
                {totalResults == 1 ? 'result!' : ' results!'}
              </p>
            )}

            <StyledMovies>

              {movies && movies.map((m) => {
                  const { Title, Poster, Plot, imdbID } = m

                  return(
                    <StyledMovieItem key={uniqueId()}>
                      <Link to={`${match.url}/${imdbID}`} onClick={setShowModal}>
                        <MovieSummary data={{Title, Poster, Plot}} />
                      </Link>

                    </StyledMovieItem>
                  )
                })
              }
              <Modal handleClose={toggleModal} show={showModal}>
                <Route
                  exact
                  path={`${ match.path }/:imdbID`}
                  render={(props) => <MovieDetail {...props} /> }
                />
              </Modal>
            </StyledMovies>
        </div>
    )

}

错误:

  

TypeError:无法读取未定义的属性“路径”

 99 |                 <Route
 100 |                   exact
101 |                   path={`${ match.path }/:imdbID`}
     |                                   ^
 102 |                   rende

该应用程序正在运行,但在测试中match参数为空。有人知道会是什么吗?

2 个答案:

答案 0 :(得分:0)

您需要将组件包装到<MemoryRouter><Router>中,例如

const wrapper =  shallow(<MemoryRouter><Route component={Movie} /></MemoryRouter>).dive().dive()

dive()是必需的,因为否则<MemoryRouter>仅呈现shallow()本身。

请参阅带有更详细说明的文章:https://medium.com/@antonybudianto/react-router-testing-with-jest-and-enzyme-17294fefd303

答案 1 :(得分:0)

如果您不想在测试中用路由器包装组件,则可以像其他任何道具一样模拟match

const mockMatch = {
  path: 'my-path/some-value',
  url: 'my-path/some-value'
}
const wrapper =  shallow(<Movie match={mockMatch}/>).toJSON()