我有一个名为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"