有了这个 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();
});
});
答案 0 :(得分:0)
import * as redux from 'react-redux'
const spy = jest.spyOn(redux, 'useSelector')
spy.mockReturnValue({ orderType:'test' })
尝试像这样模拟 useSelector。