【问题标题】:Jest test fails because it doesn't recognise a props valueJest 测试失败,因为它无法识别 props 值
【发布时间】:2021-04-07 15:09:51
【问题描述】:

拥有这个 React 函数,尝试运行测试但没有通过:

import React, { useEffect } from 'react';
import { useDispatch, useSelector, shallowEqual } from 'react-redux';
import { useIntl } from 'react-intl';
import {
  PrimaryButton,
  OutlineButton
} from 'react-komodo-design';

const Buttons = () => {
  const dispatch = useDispatch();
  const intl = useIntl();

  const orderType = useSelector(
    (state) => state.orderDetails.orderDetails.orderType,
    shallowEqual
  );

 ...

  return (
    <div>
      <OutlineButton>
        {intl.formatMessage({ id: 'buttons' })}
      </OutlineButton>
      {orderType.toLowerCase() !== 't9' && (
        <PrimaryButton
          onClick={clickReorder}
        </PrimaryButton>
      )}
    </div>
  );
};

export default Buttons;

测试文件是这样的:

import React from 'react';
import { render } from '@testing-library/react';
import Buttons from './Buttons';
import { WrapIntlProvider, WrapStore } from '../../testsHelper';

describe('<Buttons />', function () {
  it('should render <Buttons></Buttons>', () => {
    const { container } = render(
      <WrapStore>
        <WrapIntlProvider>
          <Buttons />
        </WrapIntlProvider>
      </WrapStore>
    );
    expect(container).toMatchSnapshot();
  });
});

错误消息:TypeError:无法读取未定义的属性“toLowerCase”

可以做些什么来避免这个错误?

我尝试在测试函数中添加值,如下所示:

&lt;Buttons orderType="test" /&gt;&lt;Buttons orderType={"test'} /&gt; 或将其作为变量发送:

describe('<Buttons />', function () {
  it('should render <Buttons></Buttons>', () => {
    const xx = "test"; // <--- added here
    const { container } = render(
      <WrapStore>
        <WrapIntlProvider>
          <Buttons orderType={xx} />
        </WrapIntlProvider>
      </WrapStore>
    );
    expect(container).toMatchSnapshot();
  });
});

【问题讨论】:

  • orderType.toLowerCase() 失败,因为 orderType 未定义。验证您的 useSelector 设置是否正确。
  • 我们应该在测试文件中使用 useSelector 吗?或者应该怎么做
  • 我建议您阅读 Redux 文档中的 Writing Test - Connected Components

标签: javascript reactjs unit-testing jestjs react-testing-library


【解决方案1】:
import * as redux from 'react-redux'

const spy = jest.spyOn(redux, 'useSelector')
spy.mockReturnValue({ orderType:'test' })

尝试像这样模拟 useSelector。

【讨论】:

    猜你喜欢
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 2015-07-31
    • 2019-12-17
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多