From 6d4898173a01c13f659ebc85c7ab4e1b09ae20e8 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Sun, 24 Sep 2023 13:15:23 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=92=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test/index.test.ts | 63 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 48 insertions(+), 15 deletions(-) diff --git a/test/index.test.ts b/test/index.test.ts index e2f00e8..1889f87 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -3,22 +3,22 @@ import astroRedirectFrom, { initPlugin } from '../src/index' import * as utils from '../src/utils' import * as redirects from '../src/getRedirects' +const mockLogger = { + warn: vi.fn(), + info: vi.fn(), + error: vi.fn() +} + +const hookOptionsMock = { + logger: mockLogger, + config: { + cacheDir: { pathname: './node_modules/.astro/' } + }, + command: 'dev', + updateConfig: vi.fn() +} + describe('initPlugin', () => { - const mockLogger = { - warn: vi.fn(), - info: vi.fn(), - error: vi.fn() - } - - const hookOptionsMock = { - logger: mockLogger, - config: { - cacheDir: { pathname: './node_modules/.astro/' } - }, - command: 'dev', - updateConfig: vi.fn() - } - it('should handle no markdown files scenario', async () => { const getMarkdownFilesSpy = vi.spyOn(utils, 'getMarkdownFiles') getMarkdownFilesSpy.mockResolvedValue([]) @@ -62,6 +62,19 @@ describe('initPlugin', () => { expect(mockLogger.info).toBeCalledWith('Added 1 redirects to Astro config') expect(writeJsonSpy).toBeCalled() }) + + it('should handle errors and log them', async () => { + // Make getMarkdownFiles throw an error + vi.spyOn(utils, 'getMarkdownFiles') + const getMarkdownFilesSpy = vi.spyOn(utils, 'getMarkdownFiles') + getMarkdownFilesSpy.mockImplementation(async () => { + throw new Error('Mocked error') + }) + + await initPlugin({ ...hookOptionsMock, logger: mockLogger } as any) + + expect(mockLogger.error).toHaveBeenCalledWith('Mocked error') + }) }) describe('astroRedirectFrom', () => { @@ -72,4 +85,24 @@ describe('astroRedirectFrom', () => { expect(result).toHaveProperty('hooks') expect(result.hooks).toHaveProperty('astro:config:setup') }) + + it('should call initPlugin when astro:config:setup hook is invoked', async () => { + const getMarkdownFilesSpy = vi.spyOn(utils, 'getMarkdownFiles') + getMarkdownFilesSpy.mockResolvedValue(['test.md', 'test2.md']) + + const getRedirectsSpy = vi.spyOn(redirects, 'getRedirects') + getRedirectsSpy.mockResolvedValue({ '/old': '/new' }) + + const writeJsonSpy = vi.spyOn(utils, 'writeJson') + writeJsonSpy.mockImplementation(() => Promise.resolve()) + + const integration = astroRedirectFrom() + + expect(integration.hooks).toHaveProperty('astro:config:setup') + + // Invoke the hook + if (integration.hooks['astro:config:setup']) { + await integration.hooks['astro:config:setup'](hookOptionsMock as any) + } + }) })