Skip to content

Commit

Permalink
vitest migration
Browse files Browse the repository at this point in the history
  • Loading branch information
jekrch committed Jun 23, 2024
1 parent 483216c commit 0b0aaca
Show file tree
Hide file tree
Showing 9 changed files with 207 additions and 127 deletions.
189 changes: 133 additions & 56 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
"typescript": "^5.5.2",
"vite": "^5.3.1",
"vite-tsconfig-paths": "^4.3.2",
"vitest": "^1.6.0",
"web-vitals": "^2.1.4"
},
"scripts": {
Expand All @@ -48,7 +47,8 @@
"deploy": "gh-pages -d dist"
},
"devDependencies": {
"@testing-library/react": "^14.2.2",
"@testing-library/react": "^14.3.1",
"@types/jsdom": "^21.1.7",
"@types/papaparse": "^5.3.14",
"@types/react-datepicker": "^4.19.4",
"@types/react-simple-maps": "^3.0.4",
Expand All @@ -60,6 +60,7 @@
"jsdom": "^24.1.0",
"postcss": "^8.4.38",
"postcss-cli": "^11.0.0",
"tailwindcss": "^3.3.2"
"tailwindcss": "^3.3.2",
"vitest": "^1.6.0"
}
}
2 changes: 1 addition & 1 deletion src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ code {
}

.gradient-background-modal {
background: linear-gradient(155deg, #1d2344, #1d2344, #4b2764), url(/public/noise.svg);
background: linear-gradient(155deg, #1d2344, #1d2344, #4b2764), url(/noise.svg);
filter: contrast(100%) brightness(100%);
}

Expand Down
20 changes: 10 additions & 10 deletions src/utilities/CategoryUtil.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ import { CountryContestant } from '../data/CountryContestant';
import { Category } from './CategoryUtil';
import { convertRankingsStrToArray, updateQueryParams } from './UrlUtil';

jest.mock('./UrlUtil', () => ({
convertRankingsStrToArray: jest.fn(),
updateQueryParams: jest.fn(),
vi.mock('./UrlUtil', () => ({
convertRankingsStrToArray: vi.fn(),
updateQueryParams: vi.fn(),
}));

jest.mock('../redux/actions', () => ({
setActiveCategory: jest.fn(),
setCategories: jest.fn(),
setRankedItems: jest.fn(),
setShowTotalRank: jest.fn(),
vi.mock('../redux/actions', () => ({
setActiveCategory: vi.fn(),
setCategories: vi.fn(),
setRankedItems: vi.fn(),
setShowTotalRank: vi.fn(),
}));

describe('reorderByAllWeightedRankings', () => {
Expand Down Expand Up @@ -45,8 +45,8 @@ describe('reorderByAllWeightedRankings', () => {


beforeEach(() => {
jest.clearAllMocks();
(convertRankingsStrToArray as jest.Mock).mockImplementation((ranking) => ranking.split(''));
vi.clearAllMocks();
(convertRankingsStrToArray as any).mockImplementation((ranking: any) => ranking.split(''));
});


Expand Down
37 changes: 14 additions & 23 deletions src/utilities/ContestantRepository.test.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,28 @@
import { cachedYear, initialCountryContestantCache } from "../data/InitialContestants";
import { fetchAndProcessCountryContestants } from "./ContestantRepository";
import fs from 'fs';
import path from 'path';
import fetchMock from 'jest-fetch-mock';

fetchMock.enableMocks();
import { fetchAndProcessCountryContestants, fetchCountryContestantsByYear } from "./ContestantRepository";
import { describe, it, expect, beforeEach } from 'vitest';
import { vi } from 'vitest';

beforeEach(() => {
fetchMock.resetMocks();
vi.resetAllMocks();
});

describe.skip('contestantCache validation', () => {
it('the cached contestant data should be identical to the data we would fetch otherwise', async () => {

mockFetchFromPath('contestants.csv', '../.././public/contestants.csv');
mockFetchFromPath('votes.csv', '../.././public/votes.csv');
describe('contestantCache validation', () => {
it('the cached contestant data should be returned', async () => {
const mockFetch = vi.fn();
mockFetch.mockResolvedValueOnce({ text: () => Promise.resolve('mocked vote csv data') });
mockFetch.mockResolvedValueOnce({ text: () => Promise.resolve('mocked contestant csv data') });
vi.stubGlobal('fetch', mockFetch);

const result = await fetchAndProcessCountryContestants(cachedYear, '', undefined);
const result = await fetchCountryContestantsByYear(cachedYear, '', undefined);

initialCountryContestantCache.forEach(c => {
c.contestant!.finalsRank = c.contestant?.finalsRank?.toString()?.replace('.0', '') as number | undefined;
c.contestant!.semiFinalsRank = c.contestant?.semiFinalsRank?.toString()?.replace('.0', '') as number | undefined;
return c;
})
});

expect(result).toEqual(initialCountryContestantCache);
expect(mockFetch).toHaveBeenCalledTimes(0);
});
});

async function mockFetchFromPath(endpoint: string, filePath: string) {

const csvFilePath = path.join(__dirname, filePath);
const csvData = fs.readFileSync(csvFilePath, 'utf-8');

fetchMock.mockResponseOnce(csvData);
}
});
7 changes: 3 additions & 4 deletions src/utilities/CsvCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export function fetchVoteCsv(): Promise<string> {
return cachedVoteCsvPromise;
}

const promise = fetch('/votes.csv')
const promise = fetch(`${import.meta.env.BASE_URL}votes.csv`)
.then(response => response.text());

cachedVoteCsvPromise = promise;
Expand All @@ -16,14 +16,13 @@ export function fetchVoteCsv(): Promise<string> {
let cachedContestantCsvPromise: Promise<string> | null = null;

export function fetchContestantCsv(): Promise<string> {

if (cachedContestantCsvPromise) {
return cachedContestantCsvPromise;
}

const promise = fetch('/contestants.csv')
const promise = fetch(`${import.meta.env.BASE_URL}contestants.csv`)
.then(response => response.text());

cachedContestantCsvPromise = promise;
return promise;
}
}
66 changes: 38 additions & 28 deletions src/utilities/UrlUtil.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { convertRankingsStrToArray, extractParams, updateStates } from "./UrlUtil";
import { setName, setYear, setTheme, setVote } from '../redux/actions';
import { defaultYear } from "../data/Contestants";
import { JSDOM } from 'jsdom';


// mocks for dependencies
jest.mock('redux', () => ({
Dispatch: jest.fn()
vi.mock('redux', () => ({
Dispatch: vi.fn()
}));

jest.mock('./ContestantRepository', () => ({
fetchCountryContestantsByYear: jest.fn()
vi.mock('./ContestantRepository', () => ({
fetchCountryContestantsByYear: vi.fn()
}));

function mockWindowLocationSearch(search: string) {
Expand All @@ -24,22 +25,31 @@ function mockWindowLocationSearch(search: string) {

// reset window.location to its original state after each test
afterEach(() => {
jest.restoreAllMocks();
// Reset window.location to its original state
Object.defineProperty(window, 'location', {
value: originalLocation,
writable: true
});
});

const originalLocation = window.location;
const dom = new JSDOM();
global.navigator = dom.window.navigator;

vi.restoreAllMocks();
});

describe('extractParams', () => {
let mockWindow: Window;

beforeEach(() => {
mockWindow = {
location: {
search: '',
href: 'http://localhost',
},
} as unknown as Window;
});

it('should extract parameters for a specific search string', () => {
mockWindowLocationSearch('?y=2023&r=abc&t=ab&v=f-tv&n=test');
const searchString = '?y=2023&r=abc&t=ab&v=f-tv&n=test';
mockWindow.location.search = searchString;
mockWindow.location.href = 'http://localhost' + searchString;

const params = new URLSearchParams(window.location.search);
const params = new URLSearchParams(mockWindow.location.search);
const result = extractParams(params, undefined);

expect(result).toEqual({
Expand All @@ -52,10 +62,11 @@ describe('extractParams', () => {
});

it('should extract parameters partial search string', () => {
const searchString = '?y=2023&r=abc';
mockWindow.location.search = searchString;
mockWindow.location.href = 'http://localhost' + searchString;

mockWindowLocationSearch('?y=2023&r=abc');

const params = new URLSearchParams(window.location.search);
const params = new URLSearchParams(mockWindow.location.search);
const result = extractParams(params, undefined);

expect(result).toEqual({
Expand All @@ -68,26 +79,25 @@ describe('extractParams', () => {
});
});


jest.mock('../redux/actions', () => ({
setName: jest.fn(),
setYear: jest.fn(),
setTheme: jest.fn(),
setVote: jest.fn()
vi.mock('../redux/actions', () => ({
setName: vi.fn(),
setYear: vi.fn(),
setTheme: vi.fn(),
setVote: vi.fn()
}));


// Create a mock dispatch function
const mockDispatch = jest.fn();
const mockDispatch = vi.fn();

describe('updateStates', () => {
beforeEach(() => {
// Clear all mocks before each test
mockDispatch.mockClear();
(setName as jest.Mock).mockClear();
(setYear as jest.Mock).mockClear();
(setTheme as jest.Mock).mockClear();
(setVote as jest.Mock).mockClear();
(setName as any).mockClear();
(setYear as any).mockClear();
(setTheme as any).mockClear();
(setVote as any).mockClear();
});

it('should dispatch setName when rankingName is provided', () => {
Expand Down
4 changes: 2 additions & 2 deletions src/utilities/VoteProcessor.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { updateVoteTypeCode, voteCodeHasType, voteCodeHasSourceCountry } from "./VoteProcessor";

jest.mock("./VoteRepository", () => ({
fetchVotesForYear: jest.fn()
vi.mock("./VoteRepository", () => ({
fetchVotesForYear: vi.fn()
}));


Expand Down
2 changes: 2 additions & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ export default defineConfig({
port: 3000,
},
test: {
globals: true,
environment: 'jsdom',
setupFiles: './src/setupTests.ts',
},
})

0 comments on commit 0b0aaca

Please sign in to comment.