0

我有一个以下功能组件,它将一些过滤后的数据发送到子组件。代码运行良好,即我可以运行应用程序并查看使用正确数据呈现的组件。但是我在下面写的测试失败了ChildComponent。它不是获取具有过滤值的单个数组元素,而是获取所有三个原始值。我很困惑,FilterInputBox因为道具组件的类似测试filterValue正在通过。两个测试都在相同的事件过滤器输入更改后检查更新的道具值,即handleFilterChange。我错过了什么吗?有什么建议吗?

源代码

function RootPage(props) {
  const [filterValue, setFilterValue] = useState(undefined);
  const [originalData, setOriginalData] = useState(undefined);
  const [filteredData, setFilteredData] = useState(undefined);

  const doFilter = () => {
    // do something and return some value
  }

  const handleFilterChange =  (value) => { 
    const filteredData = originalData && originalData.filter(doFilter);  
    setFilteredData(filteredData);        
    setFilterValue(value);
  };

  React.useEffect(() => {
    async function fetchData() {
        await myService.fetchOriginalData()
            .then((res) => {
                setOriginalData(res);                    
            })
    }

    fetchData();

  }, [props.someFlag]);

  return (
    <>
        <FilterInputBox
            filterValue={filterValue}
            onChange={handleFilterChange}
        />
        <ChildComponent
            data={filteredData}
        />
    </>
  );
}

测试代码

describe('RootPage', () => {
  let props,
    fetchOriginalDataStub,
    useEffectStub,
    originalData;

  const flushPromises = () => new Promise((resolve) => setImmediate(resolve));

  beforeEach(() => {
    originalData = [
        { name: 'Brown Fox' },
        { name: 'Lazy Dog' },
        { name: 'Mad Monkey' }
    ];
    fetchOriginalDataStub = sinon.stub(myService, 'fetchOriginalData').resolves(originalData);
    useEffectStub = sinon.stub(React, 'useEffect');
    useEffectStub.onCall(0).callsFake((f) => f());
    props = { ... };            
  });

  afterEach(() => {
    sinon.restore();
  });

  it('should send filtered data', async () => {
    const renderedElement = enzyme.shallow(<RootPage {...props}/>);
    const filterBoxElement = renderedElement.find(FilterInputBox);;

    await flushPromises();
    filterBoxElement.props().onChange('Lazy');
    await flushPromises();

    //This "filterValue" test is passing
    const filterBoxWithNewValue = renderedElement.find(FilterInputBox);
    expect(filterBoxWithNewValue.props().filterValue).to.equal('Lazy'); 

    //This "data" test is failing
    const childElement = renderedElement.find(ChildComponent);
    expect(childElement.props()).to.eql({
      data: [
          { name: 'Lazy Dog' }
      ]
    });
  });        
});

更新在放置一些日志语句后,我看到当我打电话时onChange originalData未定义。不知道为什么会这样,这似乎是问题所在。

如果有人对此有任何见解,仍在寻求帮助。

4

0 回答 0