我有以下组件:
import React,{ Component } from 'react'; import {Link,IndexLink} from 'react-router'; class Navbar extends Component { renderLinks = (linksData) => { return linksData.map((linkData) => { if(linkData.to === '/') { return( <div className="navbar-link-container" key={linkData.to}> <IndexLink activeClassName="navbar-active-link" to={linkData.to}> <i className="navbar-icon material-icons">{linkData.icon}</i> <span className="navbar-link-text">{linkData.text}</span> </IndexLink> </div> ) } else { return( <div className="navbar-link-container" key={linkData.to}> <Link activeClassName="navbar-active-link" to={linkData.to}> <i className="navbar-icon material-icons">{linkData.icon}</i> <span className="navbar-link-text">{linkData.text}</span> </Link> </div> ) } }) }; render() { return ( <div className={`navbar navbar-${this.props.linksData.length}`}> {this.renderLinks(this.props.linksData)} </div> ) } } Navbar.propTypes = { linksData: React.PropTypes.array.isrequired,}; export default Navbar;
现在我正在尝试编写一个单元测试来检查if条件(根据.to属性返回IndexLink或Link):
但我似乎无法测试函数的确切jsx返回,因为当我在console.log中返回一个返回时我得到了这个:
{ ‘$$typeof’: Symbol(react.element),
type: ‘div’,
key: ‘/’,
ref: null,
props:
{ className: ‘navbar-link-container’,
children:
{ ‘$$typeof’: Symbol(react.element),
type: [Object],
key: null,
props: [Object],
_owner: null,
_store: {} } },
_store: {} }
这是我到目前为止所做的测试:
it('renderLinks should return a IndexLink',() => { const wrapper = shallow(<Navbar linksData={mockLinksData}/>); const renderLinksReturn = wrapper.instance().renderLinks(mockLinksData); let foundIndexLink = false; renderLinksReturn.map((linkHtml) => { console.log(linkHtml); }); expect(foundIndexLink).toBe(true); })
现在我不知道要测试什么来查看函数是否正确运行.有没有办法像组件一样“挂载”函数的返回?或者是否有一个简单的方法来返回我可以检查的实际返回的html字符串?
解决方法
我想你不需要打电话
const renderLinksReturn = wrapper.instance().renderLinks(mockLinksData);
因为它将在渲染Navbar时被调用.
您的解决方案是正确的,但如果您想要一些其他可靠的方法来测试它.
由于此测试专门测试IndexLink并假设mockLinksData包含to =“/”
it('renderLinks should return a IndexLink when passed a link with to:\"/\"',() => { const wrapper = shallow(<Navbar linksData={mockLinksData}/>); // You can use both component name or component displayname // IndexLink or "IndexLink" expect(wrapper.find('IndexLink')).to.have.length(1); // In case you want to test whether indexLink has appropriate props or classes. const indexLink = wrapper.find(IndexLink).first(); // Check whether indexLink has pass prop expect(indexLink.props().to).to.equal("/"); // Check whether indexLink has correct classes set. expect(indexLink.hasClass('navbar-active-link')).to.equal(true); // Check whether indexLink displays the link test correctly expect(indexLink.find('navbar-link-text').text()).to.equal(mockLinksData.text); });