How do you test react state in functional component using jest and enzyme?

Viewed 181

I have a functional component called StoreLocator and want to test if its state will change or not?

I know if StoreLocator was a class component I could test it this way using instance method:

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');
  })
})

but when I try below code to achieve the same thing in functional component and hook it doesn't work:

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');
  })
})

and it says TypeError: mountedStoreLocator.chooseMap is not a function

here is the StoreLocator Component:

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


I've tested like below as @RafaelTavares mentioned in comment:


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);
    })
})

but still no luck and my test will fail by this message:

Expected: "Astoria"

Received: "none.png"
0 Answers
Related