Skip to content

Commit

Permalink
chore(jest): polyfill whatwg-fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
yifanwww committed Sep 23, 2023
1 parent f889cbd commit 21a5972
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 8 deletions.
3 changes: 2 additions & 1 deletion packages/scripts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@
"semver": "^7.5.4",
"source-map-loader": "^4.0.1",
"text-table": "^0.2.0",
"webpack": "^5.88.2"
"webpack": "^5.88.2",
"whatwg-fetch": "^3.6.18"
},
"devDependencies": {
"@jest/types": "^29.6.3",
Expand Down
6 changes: 4 additions & 2 deletions packages/scripts/src/jest/jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ function getConfig(): Config {
roots: ['<rootDir>/src'],
cacheDirectory: paths.jestCache,

setupFiles: [require.resolve('./jest.setup.js')],
setupFilesAfterEnv: hasPackageOwnTestSetup ? [packageOwnTestSetup] : [],

collectCoverageFrom: [
Expand All @@ -42,10 +43,11 @@ function getConfig(): Config {
useDefineForClassFields: true,
},
},
isModule: true,
},
],
'^.+\\.css$': paths.transforms.css,
'^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)': paths.transforms.file,
'^.+\\.css$': require.resolve('./transform.css.js'),
'^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)': require.resolve('./transform.file.js'),
},
transformIgnorePatterns: [
'[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$',
Expand Down
12 changes: 12 additions & 0 deletions packages/scripts/src/jest/jest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
declare const window: typeof globalThis;

async function setup() {
// Make sure we're in a Browser-like environment before importing polyfills
// This prevents `fetch()` from being imported in a Node test environment
if (typeof window !== 'undefined') {
// fetch() polyfill for making API calls.
await import('whatwg-fetch');
}
}

void setup();
1 change: 1 addition & 0 deletions packages/scripts/src/jest/whatwg-fetch.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module 'whatwg-fetch';
5 changes: 0 additions & 5 deletions packages/scripts/src/utils/paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,5 @@ export const paths = {
// test

jestCache: path.resolve(rootNodeModules, '.cache/jest'),

jestConfig: path.resolve(scriptsDist, 'jest/jest.config.js'),
transforms: {
css: path.resolve(scriptsDist, 'jest/transform.css.js'),
file: path.resolve(scriptsDist, 'jest/transform.file.js'),
},
};
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 21a5972

Please sign in to comment.