Created
December 31, 2024 20:04
-
-
Save oosby/24d16a6d0e06730c820772ccd68dd7f3 to your computer and use it in GitHub Desktop.
jest test a saga
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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())); | |
| } | |
| }); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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