开玩笑/酶是否有成分匹配器?

时间:2019-02-04 18:03:43

标签: javascript reactjs jestjs enzyme

我有一个返回的React组件方法和其他组件。有一个Jest匹配器来测试吗?

例如,我的组件具有以下方法:

class App extends React.Component {

  selectDashboardView(dashboard) {
    if (!dashboard) {
      return null;
    }

    switch (dashboard) {
      case DASHBOARD_TYPE.advisor:
        return <AdvisorDashboard />;

      case DASHBOARD_TYPE.advisor_fund:
        return <AdvisorFundDashboard />;

      case DASHBOARD_TYPE.portfolio:
        return <PortfolioDashboard />;

      case DASHBOARD_TYPE.investor_profile:
        return <InvestorProfileDashboard />;

      case DASHBOARD_TYPE.investment:
        return <InvestmentDashboard />;

      default:
        return null;
    }
  }
  ...
}

我希望能够编写这样的测试(显然,这不是有效的测试):

describe('App', () => {
  test('selects proper dashboard', () => {
    const wrapper = shallow(<App />);
    const instance = wrapper.instance();

    expect(instance.selectDashboardView('advisor')).toMatch(<AdvisorDashboard />);

  });
});

更新: 请务必注意,这些组件已连接到Redux。在测试<App />时,我导入了未连接的组件,与<AdvisorDashboard />相同,依此类推...可以通过以下代码解决问题:

describe('App', () => {
  test('selects proper dashboard', () => {
    const wrapper = shallow(<App setDashboard={mockFn} setIsAdvisor={mockFn} />);
    const instance = wrapper.instance();

    expect(instance.selectDashboardView('advisor').type.WrappedComponent).toEqual(AdvisorDashboard);
    expect(instance.selectDashboardView('investor_profile').type.WrappedComponent).toEqual(InvestorProfileDashboard);

  });
});

1 个答案:

答案 0 :(得分:0)

您可以尝试匹配组件名称

expect(instance.selectDashboardView('advisor').constructor.name)
 .toMatch(AdvisorDashboard.name);

或者根据doc,您可以使用type方法

expect(instance.selectDashboardView('advisor').type()).to.equal(AdvisorDashboard);