Skip to content

Instantly share code, notes, and snippets.

@markwoon
Created September 12, 2021 04:01
Show Gist options
  • Save markwoon/9041b591cf4c2ac80a1d7d5c3c3b410d to your computer and use it in GitHub Desktop.
Save markwoon/9041b591cf4c2ac80a1d7d5c3c3b410d to your computer and use it in GitHub Desktop.
Test fetch in storybook
import fetchMock from 'fetch-mock';
import {useState} from 'react';
export default {
title: 'Components/Banner/Announcement',
component: AnnouncementBanner,
parameters: {
chromatic: {
// delay to make sure animation completes before chromatic takes snapshot
delay: 3000,
},
},
};
export const Default = () => {
fetchMock.reset();
fetchMock.get('end:site/announcement', {
status: 200,
body: {
data: 'hear ye, hear ye!',
},
}, {
overwriteRoutes: true,
});
return <AnnouncementBanner />;
};
export const NoAnnouncement = () => {
fetchMock.reset();
fetchMock.get('end:site/announcement', 204);
return (
<>
<AnnouncementBanner />
<div className="storyControls">
Nothing should appear when we get `204` response from API.
</div>
</>
);
};
function AnnouncementBanner() {
const [text, setText] = useState();
fetch('http://test.com/site/announcement')
.then((response) => {
if (response.status === 204) {
console.log('204');
setText('');
} else {
response.json()
.then((json) => {
console.log('got response', json);
setText(json.data);
})
.catch((err) => console.log('error parsing json', err));
}
})
.catch((err) => console.log(err));
console.log('--', text);
if (!text) {
return null;
}
return (
<p>
{text}
</p>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment