Jest:如何确保调用React子组件

时间:2016-12-14 17:46:13

标签: unit-testing reactjs jestjs

我试图为我的一个调用多个组件的组件获得100%的测试覆盖率。我无法让Jest覆盖组件中的所有行。

// Component-test.js
import React from 'react';
import renderer from 'react-test-renderer';
import Component from './Component';

describe('CompanyOverview component', () => {
  it('should render', () => {

    const tree = renderer.create(
      <CompanyOverview params={{id: '4444'}}/>
    );
    expect(tree).toMatchSnapshot();
  });
});

以下是组件的示例代码:

// Component.js
import React from 'react';
import GetAPI from '../GetAPI';
import Employee from '../Employee';

const Component = ({ params }) => (
  <GetAPI path={`/company/${params.id}`}>
    {(company) => (
      <div>
        <h3>{company.name}</h3>
        {company.employees.map((employee, i) => (
          <Employee // <-- This isn't being picked up in the coverage. 
            firstname={employee.firstname}
            lastname={employee.lastname}
          />
     ))}
  </Fetch>
);

export default Component;

GetAPI.js

export default class Fetch extends React.Component {
  componentDidMount() {
    const { id } = this.props;
    fetch('http://example.com/' + id)
      .then((response) => response.json())
      .then((result) => this.setState({ result, loading: false }))
      .catch((error) => this.setState({ error, loading: false }));
  }

  render() {
    if (this.state.loading) {
      return (
        <p>Loading...</p>
      );
    }

    if (this.state.error) {
      return (
        <div>
          <h3>Error:</h3>
          <code>{this.state.error.message}</code>
        </div>
      );
    }

    return this.props.children(this.state.result);
  }
}

运行 jest --no-cache --verbose --coverage表明员工未在覆盖范围内被调用。

我需要嘲笑某事吗?任何帮助将不胜感激。

0 个答案:

没有答案