1
0
mirror of https://github.com/kremalicious/blog.git synced 2024-11-25 03:14:01 +01:00

test fixes

This commit is contained in:
Matthias Kretschmann 2023-11-06 13:37:27 +00:00
parent c2741c1711
commit f4faca4e51
Signed by: m
GPG Key ID: 606EEEF3C479A91F
11 changed files with 54 additions and 35 deletions

View File

@ -1,14 +1,10 @@
import { afterAll, test } from 'vitest' import { test } from 'vitest'
import fs from 'fs/promises' import fs from 'fs/promises'
import path from 'path' import path from 'path'
import { generateIcons } from './index' import { generateIcons } from './index'
const distDir = path.resolve(__dirname, 'tmp') const distDir = path.resolve(__dirname, 'tmp')
afterAll(() => {
fs.rm(path.resolve(__dirname, 'tmp'), { recursive: true })
})
test('should generate Astro & React components from SVG files', async () => { test('should generate Astro & React components from SVG files', async () => {
// Act // Act
await generateIcons(distDir) await generateIcons(distDir)
@ -45,4 +41,7 @@ test('should generate Astro & React components from SVG files', async () => {
`Example React component does not exist: ${exampleComponentPathReact}` `Example React component does not exist: ${exampleComponentPathReact}`
) )
} }
// cleanup
await fs.rm(distDir, { recursive: true, force: true })
}) })

View File

@ -22,7 +22,7 @@ function removeFolderContents(folderPath: string) {
const filePath = path.join(folderPath, file) const filePath = path.join(folderPath, file)
if (fs.lstatSync(filePath).isDirectory()) { if (fs.lstatSync(filePath).isDirectory()) {
removeFolderContents(filePath) removeFolderContents(filePath)
fs.rmdirSync(filePath) fs.rmSync(filePath)
} else { } else {
fs.unlinkSync(filePath) fs.unlinkSync(filePath)
} }

View File

@ -9,7 +9,7 @@ const destFolder = path.join('.', 'test/__fixtures__/tmp')
describe('npm run new', () => { describe('npm run new', () => {
afterEach(async () => { afterEach(async () => {
await fs.rmdir(destFolder, { recursive: true }) await fs.rm(destFolder, { recursive: true })
}) })
// Mock spinner // Mock spinner

View File

@ -1,20 +1,23 @@
import { describe, it } from 'vitest' import { describe, it } from 'vitest'
import { render, screen } from '@testing-library/react' import { render, screen, fireEvent } from '@testing-library/react'
import ExifMap from './ExifMap' import ExifMap from './ExifMap'
describe('ExifMap', () => { describe('ExifMap', () => {
it('renders without crashing', async () => { it('renders without crashing', async () => {
render( render(
<html data-theme="dark"> <>
<body> <input id="toggle" data-testid="toggle" type="checkbox" />
<input id="toggle" type="checkbox" />
<ExifMap <ExifMap
gps={{ latitude: 41.89007222222222, longitude: 12.491516666666666 }} gps={{ latitude: 41.89007222222222, longitude: 12.491516666666666 }}
/> />
</body> </>
</html>
) )
await screen.findByText(/wheel to zoom/) await screen.findByText(/wheel to zoom/)
// Simulate a change event on the checkbox
fireEvent.change(screen.getByTestId('toggle'), {
target: { checked: true }
})
}) })
}) })

View File

@ -77,7 +77,9 @@ describe('Location component', () => {
}) })
it('renders nothing and logs error when error is encountered', () => { it('renders nothing and logs error when error is encountered', () => {
const consoleErrorSpy = vi.spyOn(console, 'error') const consoleErrorSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => {})
useStoreSpy.mockImplementationOnce(() => ({ useStoreSpy.mockImplementationOnce(() => ({
data: null, data: null,
loading: false, loading: false,
@ -90,5 +92,8 @@ describe('Location component', () => {
expect(consoleErrorSpy).toHaveBeenCalledWith( expect(consoleErrorSpy).toHaveBeenCalledWith(
'Failed to fetch location: Error' 'Failed to fetch location: Error'
) )
// Restore the original console.error function after the test
consoleErrorSpy.mockRestore()
}) })
}) })

View File

@ -39,8 +39,6 @@ export function Preview() {
isDisabled={isLoading} isDisabled={isLoading}
/> />
{console.log(txConfig)}
{error || prepareError ? ( {error || prepareError ? (
<div className={styles.alert}>{error || prepareError}</div> <div className={styles.alert}>{error || prepareError}</div>
) : null} ) : null}

View File

@ -1,5 +1,5 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import useSWR from 'swr' import useSWR, { type SWRResponse } from 'swr'
import { useNetwork, useAccount } from 'wagmi' import { useNetwork, useAccount } from 'wagmi'
import type { GetToken } from './types' import type { GetToken } from './types'
@ -9,7 +9,7 @@ const apiUrl = import.meta.env.PUBLIC_WEB3_API_URL
// //
// Wrapper for fetching user tokens with swr. // Wrapper for fetching user tokens with swr.
// //
export function useFetchTokens() { export function useFetchTokens(): SWRResponse<GetToken[] | undefined, Error> {
const { chain } = useNetwork() const { chain } = useNetwork()
const { address } = useAccount() const { address } = useAccount()

View File

@ -8,6 +8,7 @@ import getCollectionPhotos from '@test/__fixtures__/getCollectionPhotos.json'
let getCollectionSpy: any let getCollectionSpy: any
let readOutExifSpy: any let readOutExifSpy: any
let consoleErrorSpy: any
beforeEach(() => { beforeEach(() => {
getCollectionSpy = vi.spyOn(astroContent, 'getCollection') getCollectionSpy = vi.spyOn(astroContent, 'getCollection')
@ -17,11 +18,14 @@ beforeEach(() => {
exif: 'mocked exif', exif: 'mocked exif',
iptc: 'mocked iptc' iptc: 'mocked iptc'
})) }))
// Silence console.error
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
}) })
afterEach(() => { afterEach(() => {
getCollectionSpy.mockRestore() getCollectionSpy.mockRestore()
readOutExifSpy.mockRestore() consoleErrorSpy.mockRestore()
}) })
describe('loadAndFormatCollection', () => { describe('loadAndFormatCollection', () => {

View File

@ -23,23 +23,36 @@ describe('getRepo Function', () => {
} }
} }
const mockFetch = async () => ({ json: async () => mockResponseData })
it('should fetch repo data', async () => { it('should fetch repo data', async () => {
const mockFetch = async () => ({ json: async () => mockResponseData })
const originalFetch = window.fetch const originalFetch = window.fetch
// Silence console.log, console.info, and console.error
const originalConsoleLog = console.log
const originalConsoleInfo = console.info
const originalConsoleError = console.error
console.log = () => {}
console.info = () => {}
console.error = () => {}
window.fetch = mockFetch as any window.fetch = mockFetch as any
const repoInfo = await getRepo('mockuser/mockrepo') const repoInfo = await getRepo('mockuser/mockrepo')
window.fetch = originalFetch
expect(repoInfo).toEqual(mockResponseData.data.user.repository) expect(repoInfo).toEqual(mockResponseData.data.user.repository)
// Restore the original fetch and console functions
window.fetch = originalFetch
console.log = originalConsoleLog
console.info = originalConsoleInfo
console.error = originalConsoleError
}) })
it('should handle errors', async () => { it('should handle errors', async () => {
const consoleMock = vi const consoleErrorMock = vi
.spyOn(console, 'error') .spyOn(console, 'error')
.mockImplementation(() => undefined) .mockImplementation(() => undefined)
const originalFetch = window.fetch const originalFetch = window.fetch
;(window as any).fetch = async () => ({ ;(window as any).fetch = async () => ({
@ -51,9 +64,9 @@ describe('getRepo Function', () => {
window.fetch = originalFetch window.fetch = originalFetch
expect(repoInfo).toBeUndefined() expect(repoInfo).toBeUndefined()
expect(consoleMock).toHaveBeenCalled() expect(consoleErrorMock).toHaveBeenCalled()
expect(consoleMock).toHaveBeenLastCalledWith(['Mock error message']) expect(consoleErrorMock).toHaveBeenLastCalledWith(['Mock error message'])
consoleMock.mockReset() consoleErrorMock.mockReset()
}) })
}) })

View File

@ -19,6 +19,7 @@ export default getViteConfig({
all: true, all: true,
exclude: [ exclude: [
'**/*.d.ts', '**/*.d.ts',
'**/types.ts',
'**/*.test.ts', '**/*.test.ts',
'**/*.spec.ts', '**/*.spec.ts',
'**/test/**/*', '**/test/**/*',

View File

@ -17,11 +17,7 @@
}, },
"typeRoots": ["./src/@types", "./node_modules/@types"] "typeRoots": ["./src/@types", "./node_modules/@types"]
}, },
"exclude": [ "exclude": ["src/images/components/**/*", "src/content"],
"src/images/components/**/*",
"src/content",
"scripts/create-icons/tmp/"
],
"include": [ "include": [
"src/**/*", "src/**/*",
"content/**/*", "content/**/*",