【发布时间】: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”
可以做些什么来避免这个错误?
我尝试在测试函数中添加值,如下所示:
<Buttons orderType="test" /> 或 <Buttons orderType={"test'} /> 或将其作为变量发送:
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