Created
December 25, 2023 08:53
-
-
Save DefectingCat/f67492a4c4533b4462e0a782daebdda8 to your computer and use it in GitHub Desktop.
Vitest mock fn
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 { existsSync, createReadStream, createWriteStream } from 'fs'; | |
import { Readable, Writable } from 'stream'; | |
import { afterEach, describe, it, vi } from 'vitest'; | |
vi.mock('fs', async (importOriginal) => ({ | |
...(await importOriginal<typeof import('fs')>()), | |
existsSync: vi.fn().mockImplementation(() => true), | |
createReadStream: vi.fn().mockImplementation(() => { | |
const stream = new Readable(); | |
stream.push('test'); | |
stream.push(null); | |
return stream; | |
}), | |
createWriteStream: vi.fn().mockImplementation(() => { | |
class MockWriter extends Writable { | |
_write( | |
chunk: string[] /* chunk: any, | |
encoding: BufferEncoding, | |
callback: (error?: Error | null | undefined) => void, */, | |
): void { | |
if (chunk.length <= 0) { | |
throw new Error('no chunk received'); | |
} | |
return; | |
} | |
} | |
const stream = new MockWriter(); | |
return stream; | |
}), | |
})); | |
vi.mocked(existsSync); | |
vi.mocked(createReadStream); | |
vi.mocked(createWriteStream); | |
describe('gzip', () => { | |
afterEach(() => { | |
vi.resetModules(); | |
}); | |
it('should gzip file', async () => { | |
const { buildGzip } = await import('./builder'); | |
await buildGzip(''); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment