我已经为组件“ CheckoutProducts”编写了单元测试,以验证其是否返回2个“ CheckoutProduct”子组件
组件层次结构为Checkout-> CheckoutProducts-> CheckoutProduct
代码如下:
//////***** Checkout.js *****//////
const products = [
{ price: 199.99, pid: 'wf', qty:2},
{ price: 9.99, pid: 'docgen', qty:3}
];
this.setState({products:products})
render ()
{
<CheckoutProducts checkoutProducts={this.state.products}/>
}
//////***** CheckoutProducts.js *****//////
const checkoutProducts = (props) => {
return (
Object.keys(props.checkoutProducts).map(productKey => (
<CheckoutProduct productName={props.checkoutProducts[productKey].pid} productQty={props.checkoutProducts[productKey].qty} />
))
);
}
//////***** CheckoutProducts.test.js *****//////
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import CheckoutProducts from './CheckoutProducts';
import CheckoutProduct from './CheckoutProduct/CheckoutProduct';
configure({adapter: new Adapter()});
describe('<CheckoutProducts />', () => {
it('should render two <CheckoutProduct /> elements', () => {
const checkoutProductsProps = [
{ price: 199.99, pid: 'wf', qty:2},
{ price: 9.99, pid: 'docgen', qty:3}
];
let wrapper = shallow(<CheckoutProducts {...checkoutProductsProps} />);
expect(wrapper.find(CheckoutProduct)).toHaveLength(2);
});
});
运行测试时出现以下错误
TypeError: Cannot convert undefined or null to object
at Function.keys (<anonymous>)
5 | return (
6 |
> 7 | Object.keys(props.checkoutProducts).map(productKey => (
| ^
8 | <CheckoutProduct productName={props.checkoutProducts[productKey].pid} productQty={props.checkoutProducts[productKey].qty} />
9 | ))
任何帮助将不胜感激!