您如何使用笑话和酶测试功能组件中的反应状态?

时间:2020-07-03 12:42:03

标签: reactjs jestjs react-hooks enzyme

我有一个名为StoreLocator的功能组件,想测试其状态是否会改变?

我知道StoreLocator是否是class组件,我可以使用instance方法以这种方式进行测试:

describe('chooseMap', () => {
  it('updates currentMap using location passed to it', () => {
    const mountedStoreLocator = shallow(<StoreLocator />);
    const mockEvent = 'testland.png';
    mountedStoreLocator.instance().chooseMap(mockEvent);
    expect(mountedStoreLocator.instance().state.currentMap).toBe('testland.png');
  })
})

但是当我尝试下面的代码来实现功能组件中的相同功能并挂接它时,它不起作用:

describe('chooseMap', () => {
  it('updates currentMap using location passed to it', () => {
    const mountedStoreLocator = shallow(<StoreLocator />);
    const mockEvent = 'testland.png';
    mountedStoreLocator.chooseMap(mockEvent);
    expect(mountedStoreLocator.currentMap).toBe('testland.png');
  })
})

它显示TypeError: mountedStoreLocator.chooseMap is not a function

这是StoreLocator组件:

export default function StoreLocator({location}) {
  const [currentMap, setCurrentMap] = useState('none.png');

    const shops = [
        {
            location: "Portland",
            address: "123 Portland Dr",
        },
        {
            location: "Astoria",
            address: "123 Astoria Dr",
        },
        {
            location: "",
            address: "",
        },
  ];
  
  const chooseMap = (location) => {
    setCurrentMap(location);
  }
  
    return (
        <div>
            <Header />
            <div>
                {shops.map((shop, index) => (
                    <Button handleClick={chooseMap} location={shop.location} key={index} />
                ))}
            </div>
            <Map imageName={currentMap} location={location} />
        </div>
    );
}

EDIT


我已经按照注释中提到的@RafaelTavares进行了如下测试:


describe('change image correctly', () => {
    it('should call handleClick on button click', () => {
        const mountedStoreLocator = shallow(<StoreLocator />);
        const map = mountedStoreLocator.find('Map');
        expect(map.prop('imageName')).toBe('none.png');
        const astoriaBtn = mountedStoreLocator.find('Button[location="Astoria"]');
        astoriaBtn.invoke('handleClick')('Astoria');
        expect(map.prop('imageName')).toBe('Astoria');
        expect(astoriaBtn.length).toBe(1);
    })
})

但仍然没有运气,我的测试将因以下消息而失败:

Expected: "Astoria"

Received: "none.png"

0 个答案:

没有答案