【问题标题】:How to get props of component when unit testing using jestjs使用 jestjs 进行单元测试时如何获取组件的 props
【发布时间】:2019-01-30 15:16:44
【问题描述】:

我正在使用浅酶。我想在测试文件中获取已传递给组件的道具。就像在示例中一样,但我变得不确定。

console.log(wrapper.props()) 

应该返回 props 的对象,但它返回一些 jsx 对象。

请协助如何获取我要为其编写测试用例的某些组件的道具。

这是我的代码:

import React from 'react';
import {
    configure,
    shallow
} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

import MenuList from './MenuList';
import {
    Link
} from 'react-router-dom';

configure({
    adapter: new Adapter()
});

const footerItem = {
    label: '',
    links: [{
        label: '',
        link: '/'
    }]
}

describe('<MenuList />', () => {

            let wrapper;
            beforeEach(() => {
                    wrapper = shallow( < MenuList footerItem = {
                            footerItem
                        }
                        / > );
                    });

                it('should render Link', () => {
                    console.log(wrapper.props().footerItem); // This should print footerItem object but returning  undefined
                    expect(wrapper.find(Link).length).toBeGreaterThan(0);
                });
            });

// and here is the code of menulist component/


import React from 'react';
import { Link } from 'react-router-dom';

const menuList = (props) => {
    let linkArray=[];
        linkArray = props.footerItem.links.map((item,index)=>{
            return <li key={index}>
                    <Link to={item.link}>
                        {item.label}
                    </Link></li>
        })

   return (
        <div className="footer-link">
            <h6>{props.footerItem.label}</h6>
                <ul>
                    {linkArray}
                </ul>
        </div>
   )
}
export default menuList;

【问题讨论】:

  • 不确定这是否会解决它,但通常在测试中从 react-router 渲染任何内容时,您应该将其包装在 MemoryRouter 中。见:github.com/ReactTraining/react-router/blob/master/packages/…
  • @MichaelCurry 这个测试用例通过了,因为我在 props 中传递了一个对象。我更想得到这个测试组件的道具。这样做有必要吗?

标签: reactjs facebook testing jestjs enzyme


【解决方案1】:
const wrapper = mount(<MyComponent foo={10} />);
expect(wrapper.props().children).to.equal(10);

编辑:

就像@Must keem 指出的那样,这也有效:

const wrapper = mount(<MyComponent foo={10} />);
expect(wrapper.instance().props.foo).to.equal(10);

【讨论】:

  • @Moyoto 我在那里添加了组件代码。我在这里使用 jestjs 来期待。所以 .to.equal(10) 变成 .toEqual(10)
  • 嗯,对我来说似乎是正确的......如果你使用 console.log(wrapper.props()) 或 console.log(wrapper.debug()) 或 console.log(wrapper,它会打印什么.dive().debug())
  • 我是如何通过 wrapper.instance().props 获得道具的。我认为只有 wrapper.props() 应该工作。 wrapper.props() 没有提供道具有什么原因吗?
猜你喜欢
  • 2017-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-10
  • 2023-03-26
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多