Created
July 1, 2023 03:48
-
-
Save spencerfeng/0c3f5326cf96c74f18209e764b1d26c5 to your computer and use it in GitHub Desktop.
For tutorial: Testing JavaScript Code with Timeouts and Promises
This file contains 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
import { jest } from '@jest/globals'; | |
import * as FetchUtils from "../fetchMessage.js"; | |
import { handleFetchedMessage } from "../handleFetchedMessage.js"; | |
describe("handleFetchedMessage", () => { | |
beforeEach(() => { | |
// 1 | |
jest.useFakeTimers() | |
}) | |
afterEach(() => { | |
// 2 | |
jest.runOnlyPendingTimers() | |
// 3 | |
jest.useRealTimers() | |
jest.resetAllMocks() | |
}) | |
it("should handle fetched message correctly", async () => { | |
const mockCallback = jest.fn() | |
jest.spyOn(FetchUtils, "fetchMessage").mockResolvedValue("Mock message") | |
handleFetchedMessage(mockCallback) | |
// 4 | |
jest.runAllTimers() | |
// 5 | |
await Promise.resolve() | |
expect(mockCallback).toHaveBeenCalledTimes(1) | |
expect(mockCallback).toHaveBeenCalledWith("Mock message") | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment