我/应该如何拆分反应集成测试?

时间:2019-06-23 03:48:35

标签: reactjs react-testing-library

我有这项测试,它可以完成3件事:

  1. 输入onChange得到更新

  2. 按钮onClick触发具有输入值的searchMovies请求

  3. 结果在文档中

测试代码:

import { searchMovies as mockSearchMovies, getPopular, getFiltered, getGenreIds } from "./tmdbAPI"

 afterEach(cleanup)

jest.mock('./tmdbAPI', () => {
  return {
    searchMovies: jest.fn(() => Promise.resolve([{ id: 1, title: "test-1", poster_path: 'test-path' }])),
    getPopular: jest.fn(() => Promise.resolve([{}])),
    getFiltered: jest.fn(() => Promise.resolve([{}])),
    getGenreIds: jest.fn(() => Promise.resolve([{}])),
  }
})

test('1. input onChange gets updated, 2. button onClick fires searchMovies request with input value, 3. Results are in the document', async () => {
  const { debug, getByPlaceholderText, getByTestId } = render(
    <Provider>
      <FindMovies />
    </Provider>
  )
  const testText = 'some movie title'
  const input = getByPlaceholderText('Search movies...')
  fireEvent.change(input, { target: { value: testText } })
  expect(input.value).toBe(testText)

  const button = getByTestId('search-button')
  fireEvent.click(button)
  expect(mockSearchMovies).toHaveBeenCalledTimes(1)
  expect(mockSearchMovies).toHaveBeenCalledWith(testText)

  await wait(() => expect(getByTestId("found-movie-item")).toBeInTheDocument())
})
  1. 我/应该如何划分此测试,以便每个test保持其“状态”,以便我可以继续进行下一个测试?

  2. 我正在提供程序中运行useEffect函数,该函数运行getPopulargetFilteredgetGenreIds异步请求。如果我不像上面的示例那样嘲笑它们,则会出现错误。有没有办法解决我目前未测试的这些不必要的模拟?

0 个答案:

没有答案