|
| 1 | +/** @jest-environment node */ |
| 2 | +import { exec } from "child_process" |
| 3 | + |
| 4 | +jest.mock(`child_process`, () => { |
| 5 | + return { |
| 6 | + exec: jest.fn(async (command, options, cb) => { |
| 7 | + setImmediate(() => { |
| 8 | + try { |
| 9 | + return cb( |
| 10 | + null, |
| 11 | + `> [email protected] install C:\\Users\\Ward\\projects\\gatsby\\gatsby\\node_modules\\sharp\n`, |
| 12 | + `` |
| 13 | + ) |
| 14 | + } catch (err) { |
| 15 | + return cb(true, ``, err.message) |
| 16 | + } |
| 17 | + }) |
| 18 | + }), |
| 19 | + } |
| 20 | +}) |
| 21 | + |
| 22 | +function getSharpInstance(): typeof import("../index") { |
| 23 | + let getSharpInstance |
| 24 | + jest.isolateModules(() => { |
| 25 | + getSharpInstance = require(`../index`) |
| 26 | + }) |
| 27 | + |
| 28 | + return getSharpInstance() |
| 29 | +} |
| 30 | + |
| 31 | +describe(`getSharpInstance`, () => { |
| 32 | + beforeEach(() => { |
| 33 | + exec.mockClear() |
| 34 | + }) |
| 35 | + |
| 36 | + // jest mocking is making this impossible to test |
| 37 | + it(`should give you the bare sharp module`, async () => { |
| 38 | + const sharpInstance = await getSharpInstance() |
| 39 | + |
| 40 | + expect(exec).not.toHaveBeenCalled() |
| 41 | + expect(sharpInstance).toBeDefined() |
| 42 | + expect(sharpInstance.versions).toBeDefined() |
| 43 | + }) |
| 44 | + |
| 45 | + it( |
| 46 | + `should rebuild sharp when binaries not found for current arch`, |
| 47 | + async () => { |
| 48 | + expect.assertions(3) |
| 49 | + |
| 50 | + let called = false |
| 51 | + jest.doMock(`sharp`, () => { |
| 52 | + if (!called) { |
| 53 | + called = true |
| 54 | + throw new Error(`sharp failed to load`) |
| 55 | + } |
| 56 | + |
| 57 | + return jest.requireActual(`sharp`) |
| 58 | + }) |
| 59 | + |
| 60 | + try { |
| 61 | + const sharpInstance = await getSharpInstance() |
| 62 | + expect(sharpInstance).toBeDefined() |
| 63 | + expect(sharpInstance.versions).toBeDefined() |
| 64 | + } catch (err) { |
| 65 | + // ignore |
| 66 | + } |
| 67 | + |
| 68 | + expect(exec).toHaveBeenCalledWith( |
| 69 | + `npm rebuild sharp`, |
| 70 | + expect.anything(), |
| 71 | + expect.anything() |
| 72 | + ) |
| 73 | + }, |
| 74 | + 60 * 1000 |
| 75 | + ) |
| 76 | +}) |
0 commit comments