Skip to content

Instantly share code, notes, and snippets.

@spencerfeng
Created July 1, 2023 03:48
Show Gist options
  • Save spencerfeng/0c3f5326cf96c74f18209e764b1d26c5 to your computer and use it in GitHub Desktop.
Save spencerfeng/0c3f5326cf96c74f18209e764b1d26c5 to your computer and use it in GitHub Desktop.
For tutorial: Testing JavaScript Code with Timeouts and Promises
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