49 lines
1.5 KiB
TypeScript
49 lines
1.5 KiB
TypeScript
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
import { hashFile } from '../fileHash'
|
|
|
|
const SHA256_OF_ABC = 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'
|
|
|
|
function fileOf(bytes: number[]) {
|
|
return new File([new Uint8Array(bytes)], 'a.png', { type: 'image/png' })
|
|
}
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals()
|
|
})
|
|
|
|
describe('hashFile', () => {
|
|
it('resolves the lowercase 64-character hex of the digest', async () => {
|
|
const digest = vi.fn(async (_algorithm: string, data: ArrayBuffer) => {
|
|
expect(Array.from(new Uint8Array(data))).toEqual([97, 98, 99])
|
|
return new Uint8Array(
|
|
SHA256_OF_ABC.match(/../g)!.map((pair) => Number.parseInt(pair, 16)),
|
|
).buffer
|
|
})
|
|
vi.stubGlobal('crypto', { subtle: { digest } })
|
|
|
|
const hex = await hashFile(fileOf([97, 98, 99]))
|
|
|
|
expect(digest).toHaveBeenCalledWith('SHA-256', expect.anything())
|
|
expect(hex).toBe(SHA256_OF_ABC)
|
|
expect(hex).toMatch(/^[0-9a-f]{64}$/)
|
|
})
|
|
|
|
it('resolves null when crypto.subtle is unavailable', async () => {
|
|
vi.stubGlobal('crypto', { subtle: undefined })
|
|
|
|
expect(await hashFile(fileOf([1]))).toBeNull()
|
|
})
|
|
|
|
it('resolves null when the digest rejects', async () => {
|
|
vi.stubGlobal('crypto', { subtle: { digest: vi.fn().mockRejectedValue(new Error('no')) } })
|
|
|
|
expect(await hashFile(fileOf([1]))).toBeNull()
|
|
})
|
|
|
|
it('imports nothing from the Media page', async () => {
|
|
const source = (await import('../fileHash?raw')).default
|
|
expect(source).not.toMatch(/import .*Media/)
|
|
expect(source).not.toMatch(/from '@\/(components|views|composables)/)
|
|
})
|
|
})
|