Skip to content

Instantly share code, notes, and snippets.

@oosby
Created December 31, 2024 20:04
Show Gist options
  • Save oosby/24d16a6d0e06730c820772ccd68dd7f3 to your computer and use it in GitHub Desktop.
Save oosby/24d16a6d0e06730c820772ccd68dd7f3 to your computer and use it in GitHub Desktop.
jest test a saga
describe("updateFooSaga", () => {
afterEach(() => {
global.fetch = jest.fn().mockReset();
});
const gen = updateFooSaga(updateFoo(mockFoo));
it("should handle successful fetch request", () => {
global.fetch = jest.fn().mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve(mockSuccessResponse),
});
gen.next(); // fetch call
expect(gen.next().value).toEqual(put(updateFooSuccess()));
});
it("should handle failed fetch request", () => {
global.fetch = jest
.fn()
.mockRejectedValueOnce(() => Promise.reject("nope"));
try {
gen.next().value; // fetch call
} catch (error) {
expect(gen.next().value).toEqual(put(updateFooError()));
}
});
});
export function* updateFooSaga({ payload }: PayloadAction<FooList>) {
try {
yield fetch(
"https://foobar.com",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
mode: "cors",
body: JSON.stringify(payload),
}
);
yield put(updateFooSuccess());
} catch (error) {
yield put(updateFooError());
}
}
export function* watchUpdateFoo() {
yield takeLatest(updateFoo.toString(), updateFooSaga);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment