Feature/unit tests (#184)

This commit is contained in:
Daniel Lautzenheiser
2022-12-04 22:15:59 -05:00
committed by GitHub
parent 255e4d8883
commit ec46a6f760
23 changed files with 1423 additions and 115 deletions

View File

@ -0,0 +1,9 @@
const path = require('path');
module.exports = {
process(src, filename) {
return {
code: `module.exports = ${JSON.stringify(path.basename(filename))};`,
};
},
};

90
core/test/mockFetch.ts Normal file
View File

@ -0,0 +1,90 @@
export const createMockRequest = <T>(
status: number,
data: {
json?: T;
text?: string;
},
options: {
contentType?: string;
headers?: Record<string, string>;
} = {},
): Response => {
const { contentType = 'application/json', headers = {} } = options;
const finalHeaders = (function () {
const data: Record<string, string> = headers;
return {
get: (key: string) => {
return data[key];
},
set: (key: string, value: string) => {
data[key] = value;
},
};
})();
finalHeaders.set('Content-Type', contentType);
return {
status,
ok: status < 400,
headers: finalHeaders,
json: () => Promise.resolve(data.json),
text: () => Promise.resolve(data.text),
} as Response;
};
export interface MockFetch {
baseUrl: string;
mocks: Record<string, Response>;
when: (url: string) => {
reply: <T>(
status: number,
data: {
json?: T;
text?: string;
},
options?: {
contentType?: string;
headers?: Record<string, string>;
},
) => void;
};
reset: () => void;
}
const mockFetch = (baseUrl: string): MockFetch => {
const mockedFetch: MockFetch = {
baseUrl,
mocks: {},
when(this: MockFetch, url: string) {
return {
reply: <T>(
status: number,
data: {
json?: T;
text?: string;
},
options?: {
contentType?: string;
headers?: Record<string, string>;
},
) => {
this.mocks[`${baseUrl}${url}`] = createMockRequest(status, data, options);
},
};
},
reset(this: MockFetch) {
this.mocks = {};
},
};
global.fetch = jest.fn().mockImplementation((url: string) => {
return Promise.resolve(mockedFetch.mocks[url.split('?')[0]]);
});
return mockedFetch;
};
export default mockFetch;

View File

@ -0,0 +1,22 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
const mockLocalStorage = (function () {
let store: Record<string, any> = {};
return {
getItem(key: string) {
return store[key] ?? null;
},
setItem(key: string, value: any) {
store[key] = value.toString();
},
clear() {
store = {};
},
removeItem(key: string) {
delete store[key];
},
};
})();
Object.defineProperty(window, 'localStorage', { value: mockLocalStorage });
export {};

14
core/test/setupEnv.js Normal file
View File

@ -0,0 +1,14 @@
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;
if (typeof window === 'undefined') {
global.window = {
URL: {
createObjectURL: jest.fn(),
},
localStorage: {
removeItem: jest.fn(),
getItem: jest.fn(),
},
};
}