开玩笑:如何测试分派API操作的组件

时间:2019-03-05 09:50:06

标签: jestjs react-testing-library

我是测试新手, 我试图了解是否有可能测试从组件分派的API调用。 是否可以等待服务器的响应?

import React from 'react';
import { render, fireEvent, cleanup, waitForElement } from 'react-testing-library';
import 'jest-dom/extend-expect'

import App from 'src/app';

import { store } from 'stories/index.stories.js';
import { Provider, connect } from 'react-redux';

const renderComponent = () => (<App />);

it('renders correctly', () => {

  const { container, getByText, queryAllByText, getByPlaceholderText } = renderComponent();

  expect(container).not.toBeEmpty();

  expect(getByText(/Discover/i)).toBeTruthy();

  const discoverBtn = getByText(/Discover/i);

  fireEvent.click(discoverBtn); // this will dispatch an action from the component

  //what should i do next ?
});

1 个答案:

答案 0 :(得分:1)

这就是我的方法。

首先,我将所有fetch请求放在一个单独的文件中,例如/api/index.js。这样,我可以在测试中轻松模拟它们。

然后我执行用户将要执行的操作。最后,我检查API是否已被调用以及DOM是否已正确更新。

import { aFetchMethod } from './api'

// With jest.mock our API method does nothing
// we don't want to hit the server in our tests
jest.mock('./api')

it('renders correctly', async () => {
  const { getByText } = render(<App />)

  aFetchMethod.mockResolvedValueOnce('some data that makes sense for you')
  fireEvent.click(getByText('Discover'))

  expect(aFetchMethod).toHaveBeenCalledTimes(1)
  expect(aFetchMethod).toHaveBeenCalledWith('whatever you call it with')

  // Let's assume you now render the returned data
  await wait(() => getByText('some data that makes sense for you'))
})