首页 > 解决方案 > 您如何使用 jest 和酶测试功能组件中的反应状态?

问题描述

我有一个名为的功能组件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"

标签: reactjsjestjsreact-hooksenzyme

解决方案


推荐阅读