From a47a87a1158fd0f2af7f5bc917d5e47c05334c5a Mon Sep 17 00:00:00 2001 From: Kevin Barabash Date: Tue, 9 Jul 2024 17:36:50 -0400 Subject: [PATCH 1/2] provide an example of how to mock singletons in jest tests --- src/react-render-perf/lesson-03/content.mdx | 46 ++++++++++++++++++++- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/src/react-render-perf/lesson-03/content.mdx b/src/react-render-perf/lesson-03/content.mdx index d88fd07..3f554f2 100644 --- a/src/react-render-perf/lesson-03/content.mdx +++ b/src/react-render-perf/lesson-03/content.mdx @@ -77,10 +77,52 @@ While singletons are sometimes frowned upon because they can make testing more difficult in some languages, that isn't the case in JavaScript. It's easy to mock the singleton using jest if follow these guidelines: -- Export the singleton from its own file. TODO(kevinb): provide an example of how to - mock the singleton. - If you have a custom class instead of using EventEmitter be sure to export that as well so that you can use it when mocking the singleton. +- Instead of exporting the singleton directly, export a function that returns the + singleton. This will allow you to mock the singleton on a per-test basis. + +```ts +// my-awesome-event-emitter.ts +export class MyAwesomeEventEmitter { + ... +} + +// This is our singleton. Note that it isn't being exported. +// Instead, we want people to use the function below to get +// the singleton. +const myAwesomeEventEmitter = new MyAwesomeEventEmitter(); + +export const getMyAwesomeEventEmitter = () => myAwesomeEventEmitter; +``` + +When writing tests you import both the class and the singleton getter into your test +file to help with mocking. + +```ts +// foo.test.ts +import * as MyAwesomeEventEmitter from "../my-awesome-event-emitter" + +describe("Foo", () => { + it("should function as expected", () => { + // Arrange + const mockEmitter = new MyAwesomeEventEmitter(); + // modify the state of mockEmitter if necessary. + jest.spyOn( + MyAwesomeEventEmitter, "getMyAwesomeEventEmitter" + ).mockReturnValue( + mockEmitter, + ); + // Now the code under test will be using `mockEmitter` instead of + // the `myAwesomeEventEmitter` that we created in my-awesome-event-emitter.ts. + + // Act + // ... + + // Assert + // ... + }); +}); ### State From bbfebd2a069689da646884db57aab8bbe3455c9f Mon Sep 17 00:00:00 2001 From: Kevin Barabash Date: Tue, 9 Jul 2024 17:39:50 -0400 Subject: [PATCH 2/2] add closing triple-backtick --- src/react-render-perf/lesson-03/content.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/src/react-render-perf/lesson-03/content.mdx b/src/react-render-perf/lesson-03/content.mdx index 3f554f2..a4e327c 100644 --- a/src/react-render-perf/lesson-03/content.mdx +++ b/src/react-render-perf/lesson-03/content.mdx @@ -123,6 +123,7 @@ describe("Foo", () => { // ... }); }); +``` ### State