如何测试取决于参数的开关盒?

时间:2019-01-28 23:33:15

标签: javascript reactjs ecmascript-6 jestjs enzyme

我有这个:

runs_controller.rb

在组件的# Never trust parameters from the scary internet, only allow the white list through. def run_params params.require(:run).permit(... other fields... , :date) end 语句上调用了结尾:

  const renderComponents = () => {
    switch (selectedService) {
      case 'otherservices':
        return <SoftLayerCancellationRequests />;
      case 'dedicatedhosts':
        return <GetDedicatedHostsCancellations />;
      case 'virtualguestsservers':
        return <SoftLayerGetVirtualGuests />;
      case 'baremetalservers':
        return <GetBareMetalServersCancellations />;
      default:
        return null;
    }
  };

return参数来自商店:

return (
    <>
      <Header pageTitle={t('cancellations.header')} />

            {accountId ? (
              <>
                <TableToolbarComp />
                {renderComponents()}
              </>
            ) : (
              <UpgradeMessage />
            )}

    </>
  );

我该怎么做才能测试该开关盒?

1 个答案:

答案 0 :(得分:0)

renderComponents下的函数应接受selectedService作为参数:

const renderComponents = (selectedService) => {
  switch (selectedService) {
    // ...
  }
};

通过不依赖闭包,该函数变得纯净,并且更易于进行单元测试:

it('renders a SoftLayerCancellationRequests when passed "otherservices" as parameter', () => {
  const wrapper = shallow(renderComponents('otherservices'));
  expect(wrapper.find(SoftLayerCancellationRequests)).toHaveLength(1);
})

但是,我在这种测试中看不到什么价值。这是因为该函数基本上充当一个简单的映射:

const serviceToComponent : {
  otherservices: SoftLayerCancellationRequests,
  dedicatedhosts: GetDedicatedHostsCancellations,
  virtualguestsservers: SoftLayerGetVirtualGuests,
  baremetalservers: GetBareMetalServersCancellations
}

测试似乎有些乏味。

更有意义的测试是测试使用这种映射的组件的行为。