Skip to content

Commit

Permalink
fix/jest module mapping (umijs#8293)
Browse files Browse the repository at this point in the history
* fix(umi-test): 🐛 fix jest moduleNameMap only do map once

* refactor: 🎨 mv jsdom setup to jest setupfiles config

* test: ✅ smoke test for import from umi in test

* chore: ⬆️ update test-library/react to remove warnings
import js-dom expect types

* fix: 🐛 add back react
wait esbuild to support react-jsx

* refactor: 🔥 remove include fields

* refactor: 🎨 setup testing-library/js-dom when use testing-library/react

* refactor: 🎨 use startsWith to determine alias matches

* refactor: 🎨  support dva$ alias config

* chore: 🔧 jsx use react
due to esbuild is not fully supoort react-jsx

* refactor: 🎨 test case remove umi context

Co-authored-by: pshu <[email protected]>
  • Loading branch information
stormslowly and stormslowly authored Jun 29, 2022
1 parent 295052b commit 3c1136b
Show file tree
Hide file tree
Showing 11 changed files with 120 additions and 37 deletions.
7 changes: 7 additions & 0 deletions examples/test-test/.umirc.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
export default {
npmClient: 'pnpm',
plugins: ['@umijs/plugins/dist/dva'],
dva: {
immer: {
enableES5: true,
enableAllPlugins: true,
},
},
};
9 changes: 4 additions & 5 deletions examples/test-test/components/Greet/Greet.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import '@testing-library/jest-dom';
import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import Greet from './Greet';
Expand All @@ -24,18 +23,18 @@ test('renders Greet without name by snapshot', () => {
});

test('renders Greet without name assert by testing-library', () => {
const { container } = render(<Greet />);
render(<Greet />);

const greetDom = screen.getByText('Anonymous');
expect(greetDom).toBeInTheDocument();
});

test('Greet click', async () => {
const onClick = jest.fn();
const { container } = render(<Greet onClick={onClick} />);
render(<Greet onClick={onClick} />);

const greetDom = screen.getByText('Anonymous');
await fireEvent.click(screen.getByText(/hello/i));
screen.getByText('Anonymous');
fireEvent.click(screen.getByText(/hello/i));

expect(onClick).toBeCalledTimes(1);
});
8 changes: 8 additions & 0 deletions examples/test-test/importFromUmiSmoke.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// @ts-ignore
import { connect } from 'dva';
import { useAppData } from 'umi';

test('import from umi works', () => {
expect(useAppData).toBeDefined();
expect(connect).toBeDefined();
});
1 change: 1 addition & 0 deletions examples/test-test/jest-setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import '@testing-library/jest-dom';
1 change: 1 addition & 0 deletions examples/test-test/jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ const jestConfig = createConfig({
export default async () => {
return (await configUmiAlias({
...jestConfig,
setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],
})) as Config.InitialOptions;
};
4 changes: 3 additions & 1 deletion examples/test-test/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
"test": "jest"
},
"dependencies": {
"@umijs/plugins": "workspace:4.0.0-canary.20220628.2",
"umi": "4.0.0-canary.20220628.2"
},
"devDependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^12",
"@testing-library/react": "^13",
"@types/jest": "^27.5.1",
"@types/testing-library__jest-dom": "^5.14.5",
"jest": "^27",
"ts-node": "^10",
"typescript": "^4.7.2"
Expand Down
6 changes: 6 additions & 0 deletions examples/test-test/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"extends": "./.umi/tsconfig.json",
"compilerOptions": {
"jsx": "react"
}
}
14 changes: 13 additions & 1 deletion packages/preset-umi/src/commands/generators/jest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,23 @@ export default (api: IApi) => {
const packageToInstall: Record<string, string> = res.willUseTLR
? {
...basicDeps,
'@testing-library/react': '^12',
'@testing-library/react': '^13',
'@testing-library/jest-dom': '^5.16.4',
'@types/testing-library__jest-dom': '^5.14.5',
}
: basicDeps;
h.addDevDeps(packageToInstall);
h.addScript('test', 'jest');

if (res.willUseTLR) {
writeFileSync(
join(api.cwd, 'jest-setup.ts'),
`import '@testing-library/jest-dom';
`.trimLeft(),
);
logger.info('Write jest-setup.ts');
}

const importSource = api.appData.umi.importSource;
writeFileSync(
join(api.cwd, 'jest.config.ts'),
Expand All @@ -60,6 +71,7 @@ export default async () => {
...createConfig({
target: 'browser',
}),
${res.willUseTLR ? `setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],` : ''}
// if you require some es-module npm package, please uncomment below line and insert your package name
// transformIgnorePatterns: ['node_modules/(?!.*(lodash-es|your-es-pkg-name)/)']
})) as Config.InitialOptions;
Expand Down
43 changes: 43 additions & 0 deletions packages/umi/src/test.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { getAliasPathWithKey } from './test';

test('simple alias to jest moduleNameMapper', () => {
const p = getAliasPathWithKey(
{
'react-dom': '/path/to/react-dom',
},
'react-dom',
);
expect(p).toBe('/path/to/react-dom');
});

test('double alias path', () => {
const p = getAliasPathWithKey(
{
alias1: 'alias2/lib',
alias2: '/path/to/module',
},
'alias1',
);
expect(p).toBe('/path/to/module/lib');
});

test('double alias path suffixed $', () => {
const p = getAliasPathWithKey(
{
endWith$: '/path/to/index.js',
},
'endWith$',
);
expect(p).toBe('/path/to/index.js');
});

test('overlapped alias paths', () => {
const p = getAliasPathWithKey(
{
common$: '/path/to/index.js',
'common/lib': '/path/to/lib',
},
'common/lib',
);
expect(p).toBe('/path/to/lib');
});
26 changes: 20 additions & 6 deletions packages/umi/src/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,27 @@ import { Service } from './service/service';

export * from '@umijs/test';

function getAliasPathWithKey(
export function getAliasPathWithKey(
alias: Record<string, string>,
key: string,
): string {
const thePath = alias[key];
if (alias[thePath]) {
return getAliasPathWithKey(alias, thePath);
if (alias[key]) {
return getAliasPathWithKey(alias, alias[key]);
}

const aliasKeys = Object.keys(alias);
const keyStartedWith = aliasKeys.find(
(k) => !k.endsWith('$') && key.startsWith(`${k}/`),
);

if (keyStartedWith) {
const realPath = alias[keyStartedWith];
const newKey = realPath + key.slice(keyStartedWith.length);

return getAliasPathWithKey(alias, newKey);
} else {
return key;
}
return thePath;
}

let service: Service;
Expand All @@ -33,7 +45,9 @@ export async function configUmiAlias(config: Config.InitialOptions) {
const alias = await getUmiAlias();
for (const key of Object.keys(alias)) {
const aliasPath = getAliasPathWithKey(alias, key);
if (existsSync(aliasPath) && statSync(aliasPath).isDirectory()) {
if (key.endsWith('$')) {
config.moduleNameMapper[`^${key}`] = aliasPath;
} else if (existsSync(aliasPath) && statSync(aliasPath).isDirectory()) {
config.moduleNameMapper[`^${key}/(.*)$`] = `${aliasPath}/$1`;
config.moduleNameMapper[`^${key}$`] = aliasPath;
} else {
Expand Down
38 changes: 14 additions & 24 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 3c1136b

Please sign in to comment.