Reactjs 如何使用jest和酶测试功能成分的反应状态?
我有一个名为Reactjs 如何使用jest和酶测试功能成分的反应状态?,reactjs,jestjs,react-hooks,enzyme,Reactjs,Jestjs,React Hooks,Enzyme,我有一个名为StoreLocator的功能组件,想测试它的状态是否会改变 我知道如果StoreLocator是类组件,我可以使用实例方法对其进行测试: describe('chooseMap', () => { it('updates currentMap using location passed to it', () => { const mountedStoreLocator = shallow(<StoreLocator />); const
StoreLocator
的功能组件,想测试它的状态是否会改变
我知道如果StoreLocator
是类
组件,我可以使用实例
方法对其进行测试:
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');
})
})
编辑
在评论中提到@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);
})
})
你没有;组件的状态是内部的,它是一个实现细节。通过组件的公共API:props和DOM测试组件。你是说没有办法在功能组件中测试状态?要“测试状态”,你应该模拟点击按钮,然后检查
映射
prop。这样做你是在测试行为,而不是Jornsharpe指出的实现细节。谢谢@RafaelTavares,我已经编辑了答案并尝试了你的建议,但仍然没有成功
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>
);
}
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"