.github
.husky
.vscode
packages
app
core
dev-test
src
test
data
harnesses
fileTransformer.js
globalSetup.js
mockFetch.ts
mockLocalStorage.ts
setupEnv.js
test-utils.tsx
tsconfig.json
.editorconfig
.eslintignore
.eslintrc.js
.gitignore
.prettierignore
.prettierrc
babel.config.js
jest.config.integration.js
jest.config.js
package.json
postcss.config.js
tailwind.config.js
tsconfig.base.json
tsconfig.dev.json
tsconfig.json
webpack.config.js
demo
docs
.all-contributorsrc
.eslintignore
.gitattributes
.gitignore
.nvmrc
CODE_OF_CONDUCT.md
CONTRIBUTING.md
LICENSE
README.md
lerna.json
netlify.toml
nx.json
package.json
renovate.json
static-cms-icon.png
static-cms-logo.png
tailwind.base.config.js
yarn.lock
91 lines
1.9 KiB
TypeScript
91 lines
1.9 KiB
TypeScript
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;
|