Skip to content

feat: add image pre-loading hooks #10015

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
wip: commit progress for tests
  • Loading branch information
Parkreiner committed Oct 4, 2023
commit 2c987ba4be50bc482f8cbcd354181978b7b434f0
53 changes: 39 additions & 14 deletions site/src/hooks/images.test.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,60 @@
/**
* Work in progress. Mainly because I need to figure out how best to deal with
* a global constructor that implicitly makes HTTP requests in the background.
*/
import { useImagePreloading, useThrottledImageLoader } from "./images";

/**
* Probably not on the right track with this one. Probably need to redo.
* This is weird and clunky, and the mocking seems to have more edge cases than
* the code I'm trying to test.
*
* HTMLImageElement doesn't go through fetch, but still it might be worth trying
* to integrate this with MSW
*/
let mode: "alwaysSucceed" | "alwaysFail" = "alwaysSucceed";

class MockImage {
#unusedWidth = 0;
#unusedHeight = 0;
#src = "";
completed = false;

constructor(width?: number, height?: number) {
this.#unusedWidth = width ?? 0;
this.#unusedHeight = height ?? 0;
}
onload: (() => void) | undefined = undefined;
onerror: (() => void) | undefined = undefined;

get src() {
return this.#src;
}

set src(newSrc: string) {
this.#src = newSrc;
this.#simulateHttpRequest(newSrc);
}

#simulateHttpRequest(src: string) {
const promise = new Promise<void>((resolve, reject) => {
if (src === "") {
reject();
}

const settlePromise = mode === "alwaysSucceed" ? resolve : reject;
setTimeout(settlePromise, 100);
});

// Need arrow functions because onload/onerror are allowed to mutate in the
// original HTMLImageElement
void promise.then(() => this.onload?.());
void promise.catch(() => this.onerror?.());
}
}

beforeAll(() => {
jest.useFakeTimers();
jest.spyOn(global, "Image").mockImplementation(MockImage);

jest.spyOn(global, "Image").mockImplementation(() => {
return new MockImage() as unknown as HTMLImageElement;
});
});

beforeEach(() => {
mode = "alwaysSucceed";
});

afterAll(() => {
jest.useRealTimers();
jest.clearAllMocks();
});

test(`${useImagePreloading.name}`, () => {
Expand Down