标签: react-testing-library

React测试库:测试属性/属性

我正在使用TypeScript编写React应用程序。我将material-ui用于组件,将react-testing-library用于单元测试。

我正在为material-ui的Grid组件编写包装器,以便始终有一个项目。

import Grid from "@material-ui/core/Grid";
import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles";
import React, { PureComponent } from "react";
import styles from "./styles";

export interface OwnProps {
  className?: string;
}

export interface Props extends WithStyles<typeof styles>, OwnProps {}

export interface DefaultProps {
  className: string;
}

export class GridItem extends PureComponent<Props & DefaultProps> {
  static defaultProps: DefaultProps = {
    className: ""
  };

  render() {
    const { classes, children, className, ...rest } = this.props;
    return (
      <Grid
        data-testid="grid-item"
        item={true}
        {...rest}
        className={classes.grid …
Run Code Online (Sandbox Code Playgroud)

unit-testing typescript reactjs jestjs react-testing-library

6
推荐指数
3
解决办法
6364
查看次数

如何使用react-testing-library测试react-select

App.js

import React, { Component } from "react";
import Select from "react-select";

const SELECT_OPTIONS = ["FOO", "BAR"].map(e => {
  return { value: e, label: e };
});

class App extends Component {
  state = {
    selected: SELECT_OPTIONS[0].value
  };

  handleSelectChange = e => {
    this.setState({ selected: e.value });
  };

  render() {
    const { selected } = this.state;
    const value = { value: selected, label: selected };
    return (
      <div className="App">
        <div data-testid="select">
          <Select
            multi={false}
            value={value}
            options={SELECT_OPTIONS}
            onChange={this.handleSelectChange}
          />
        </div>
        <p data-testid="select-output">{selected}</p> …
Run Code Online (Sandbox Code Playgroud)

integration-testing reactjs react-select react-testing-library

6
推荐指数
5
解决办法
4903
查看次数

使用 domjs 时无法使 refs 工作,经 React 测试库测试

这是一个关于在规范中使用 React refs 的问题。具体来说,我在浏览器中看到的行为与在测试中运行时看到的行为不同。

// app_container.test.js

import React from 'react'
import ReactDOM from 'react-dom'
import AppContainer from "./app_container"
import { render, fireEvent, waitForElement, cleanup, wait } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import axiosMock from 'axios'

import { useAsync } from "react-use"

afterEach(cleanup);

test("renders", () => {
  const { getByTestId } = render(<AppContainer />);
  expect(getByTestId("app-container")).toHaveClass("app-container");

});


test("when mounted, it loads the rings", async () => {
  jest.setTimeout(15000);

  const { getByTestId } = render(<AppContainer />);

  const container = getByTestId('app-container')

  await wait(() => expect(getByText("Abc")).toBeInTheDocument()); …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-testing-library react-ref

6
推荐指数
0
解决办法
1123
查看次数

@testing-library/react TDD,react-bootstrap:这种测试有用还是只是时间宽松

我尝试用 TDD 视图编写代码,我一直遇到同样的问题,我应该测试什么,不应该测试什么,目标是使用 TDD 制作一个基于 React-bootstrap 的导航栏,我的组件将只是一个具有较少属性的包装器,以使其变得简单,我从react-bootstrap中Navbar的品牌子组件开始。最终目标是测试反映用户应该测试的内容,例如导航中存在具有良好 src 和 alt 属性的品牌徽标 img。

这些测试有趣还是应该避免?

我的测试

import React from 'react';
import { render } from '@testing-library/react';
import BrandNav from './BrandNav';

test('testing brand navigation', () => {
    const altProp = 'message to show if image unavailable',
        srcProp = 'relativeFilePath',
        host = window.location;

    const { getByAltText } = render(<BrandNav alt={altProp} src={srcProp} />);

    const brandLogo = getByAltText(altProp);
    expect(brandLogo.src).toEqual(`${host}${srcProp}`);
});
Run Code Online (Sandbox Code Playgroud)

我的组件

import React from 'react';
import { Navbar } from 'react-bootstrap';

const BrandNav = ({ alt, …
Run Code Online (Sandbox Code Playgroud)

tdd reactjs jestjs react-bootstrap react-testing-library

6
推荐指数
1
解决办法
1607
查看次数

React-testing-library 模拟 axios.create({}) 实例

我想用react-testing-library测试我的api 并且我从一个名为 apiClient.ts 的文件中导出由 axios.create 创建的实例

import axios from 'axios'

const apiClient = axios.create({
  baseURL: process.env.REACT_APP_API_URL,
  responseType: 'json',
  headers: {
    'Content-Type': 'application/json',
  },
})

export default apiClient
Run Code Online (Sandbox Code Playgroud)

然后在 users.ts fetchUsersApi 中使用我从 apiClient 获取的 axios 实例

import apiClient from './apiClient'

export interface ITrader {
  id: number
  name: string
  username: string
  email: string
  address: any
  phone: string
  website: string
  company: any
}

export const fetchTradersApi = async (): Promise<ITrader[]> => {
  const response = await apiClient.get<ITrader[]>('/users')
  return response.data
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个 …

mocking reactjs axios react-testing-library

6
推荐指数
1
解决办法
6820
查看次数

useSelector 未定义

您好,我正在为其中包含 redux 的组件编写单元测试。在测试它时,抛出错误 UseSelector state undefined。UseSelector 将在收到 api 响应后更新一次。直到它的值是未定义的。但是,在进行单元测试时,它会在第一个本身上引发错误。如何克服这个问题。

测试文件

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { act } from 'react-dom/test-utils';
import '@testing-library/jest-dom/extend-expect';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import LinkApplication from '../index';
import {reducer} from '../../../redux/summary/reducer';
let INITIAL_STATES = {
    isFetching: false,
    errorMessage: "",
    requestExtensionErrorMessage: "",
    requestExtensionSuccessMessage: "",
    linkApplicationSuccess: "",
    linkApplicationFailure: null,
    linkLoanSuccessMessage: "",
    linkLoanErrorMessage: "",
    LinkApplicationErrorMessage:"",
  };
function renderWithRedux(
  component,
  { INITIAL_STATES, store = createStore(reducer, INITIAL_STATES) …
Run Code Online (Sandbox Code Playgroud)

reactjs react-testing-library

6
推荐指数
1
解决办法
4965
查看次数

Jest 模拟无法与 React 测试库一起使用

我用于@testing-library/react测试 UI 组件。无法让笑话模拟工作。

它似乎无法模拟导出函数的实现getDomElement,但会调用实际的实现。

Table.test.js 的实现

describe('Table', () => {
  jest.mock('../../../../commonHelpers/getDomElement.js', () => {});

  it('it renders columns', () => {
    render(
      <ThemeProvider>
        <Table
          columns={columns}
          data={data}         
        />
      </ThemeProvider>,
    );
  })
})
Run Code Online (Sandbox Code Playgroud)

Table.js 的实现

import React, { useEffect } from 'react';
import PropTypes from 'prop-types';

import {
  useTable,
  useSortBy,
  useBlockLayout,
  useResizeColumns,
  usePagination,
} from 'react-table';

import { TableStyled as Table, TableContainer } from './styled';
import Pagination from './Pagination';
import Head from './Head';
import Body from './Body';
import TableContext …
Run Code Online (Sandbox Code Playgroud)

javascript mocking jestjs react-testing-library

6
推荐指数
1
解决办法
7084
查看次数

Tooltip MUI 和 React 测试库

我正在尝试在我的 React 应用程序上测试 Info HOC:

const InfoHOC = (HocComponent) => ({ message }) => (
  <>
    <Tooltip title={message}>
      <InfoIcon />
    </Tooltip>
    {HocComponent}
  </>
);

export default InfoHOC;
Run Code Online (Sandbox Code Playgroud)

我已经简化了。但由于它使用 Material ui Tooltip 组件,我无法测试鼠标悬停时是否显示消息...

it('should display info message on <div /> mouseover', () => {
  const Component = InfoHoc(<div>jest div</div>)({ message: 'jest infoHoc message' });
  const { getByTitle, getByDisplayValue } = render(Component);
  const icon = getByTitle('jest infoHoc message');
  act(() => {
    fireEvent(
      icon,
      new MouseEvent('mouseover', {
        bubbles: true,
      }),
    );
  });
  expect(getByDisplayValue('jest …
Run Code Online (Sandbox Code Playgroud)

material-ui react-testing-library

6
推荐指数
2
解决办法
8785
查看次数

如何使用 React 测试库测试 `contenteditable` 事件

我正在尝试为我们的富文本组件之一编写测试,该组件是使用 React js 中的 slate js 编辑器实现的。因此,在编写测试时,我正在检索元素 div[contenteditable='true'],但无法模拟更改、模糊、焦点等事件。附加到编辑器组件的处理程序不会被调用。我尝试了多种组合,但没有成功。有人可以帮忙吗?是否可以使用测试库模拟 contenteditable 元素的事件(contenteditable 使用 slatejs 实现)?

contenteditable reactjs slatejs react-testing-library testing-library

6
推荐指数
1
解决办法
2609
查看次数

如何在反应测试库/笑话中模拟对 IndexedDB 的请求?

我有一个组件,在数据检索完成之前显示一个旋转器。但我不从服务器获取数据,而是使用 Dexie 库从 indexedDB 获取数据。我怎么能嘲笑这样的要求。我的代码:

组件内的 useEffect

  useEffect(() => {
      dispatch(setData())
    }, [])
   
    if(isDataLoadng) {
      return <Spinner/>
    }
    
    return Component
Run Code Online (Sandbox Code Playgroud)

重击动作

import db from '../../indexedDB/db'

    export const setData = createAsyncThunk(
      `setData`,
      async (_, { getState }) => {
          const data =await db.data.toArray()
          return {data}
      }
    )
Run Code Online (Sandbox Code Playgroud)

索引数据库文件

import Dexie from 'dexie';


const db = new Dexie("dataDB");
db.version(1).stores({
  data: 'id, name,
});


export default db
Run Code Online (Sandbox Code Playgroud)

我的减速机

const initialState = {
  data: [],
  isDataLoading: true,
}

const crudSlice = createSlice({
  name: 'dataReducer', …
Run Code Online (Sandbox Code Playgroud)

reactjs react-testing-library

6
推荐指数
0
解决办法
1053
查看次数