【问题标题】:Jest: How to test a component that dispatch an API action笑话:如何测试调度 API 操作的组件
【发布时间】:2019-07-26 17:56:15
【问题描述】:

我是测试新手, 我试图了解是否可以测试从组件调度的 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 ?
});

【问题讨论】:

  • 你能添加你目前的代码吗?这些小信息对您的帮助很重要
  • 我正在编辑问题
  • 这取决于你点击按钮时应该发生什么

标签: jestjs react-testing-library


【解决方案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'))
})

【讨论】:

    猜你喜欢
    • 2021-06-13
    • 1970-01-01
    • 2020-06-14
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2015-10-17
    • 1970-01-01
    相关资源
    最近更新 更多