期待True时,Jest返回False

时间:2017-12-15 16:49:15

标签: reactjs jestjs enzyme

我试图使用Jest和Enzyme在React中测试组件。

我想资产我的导航组件渲染NavItems。

测试

import React from 'react';
import { shallow } from 'enzyme';

import Navigation from '../src/components/navigation/Navigation';
import NavItem from '../src/components/navigation/NavItem';

describe('.Navigation Component', () => {
  it('should contain NavItem', () => {
    const wrapper = shallow(<Navigation />);
    console.log(wrapper.debug());
    expect(wrapper.contains(<NavItem {...mockNavitem} />)).toEqual(true);
  });
});

const mockNavitem = { href: 'foo', text: 'bar', activeClass: 'boo' };

导航组件:

import React from 'react';
import NavItem from './NavItem';

const navItems = [
  {
    id: 0,
    href: '/',
    text: 'Home',
    activeClass: '',
  },
  {
    id: 1,
    href: '/page-two',
    text: 'Page Two',
    activeClass: '',
  },
];

const Navigation = () => (
  <ul>
    {navItems.map(item => (
      <li key={item.id}>
        <NavItem {...item} />
      </li>
    ))}
  </ul>
);

export default Navigation;

NavItems组件:

import React from 'react';
import PropTypes from 'prop-types';
import { NavLink } from 'react-router-dom';

const NavItem = ({ href, text, activeClass }) => (
  <NavLink to={href} activeClassName={activeClass}>
    {text}
  </NavLink>
);

NavItem.propTypes = {
  href: PropTypes.string.isRequired,
  text: PropTypes.string.isRequired,
  activeClass: PropTypes.string.isRequired,
};

export default NavItem;

测试运行器的输出如下:

 FAIL  __tests__/Navigation.test.jsx
  ● Console

    console.log __tests__/Navigation.test.jsx:10
      <ul>
        <li>
          <NavItem id={0} href="/" text="Home" activeClass="" />
        </li>
        <li>
          <NavItem id={1} href="/page-two" text="Page Two" activeClass="" />
        </li>
      </ul>

  ● .Navigation Component › should contain NavItem

    expect(received).toEqual(expected)

    Expected value to equal:
      true
    Received:
      false

我添加了一个控制台日志语句来输出组件,我可以在结果中看到它,但它似乎不是一个有效的测试。

我很反应/开玩笑,所以我可能犯了一个非常错误的错误。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

尝试遍历Navigation组件以查找NavItem

expect(wrapper.find(NavItem)).toHaveLength(1);