Skip to content

Commit

Permalink
feat: mock support _mock.ts and **/mock/** under src, Close #4077
Browse files Browse the repository at this point in the history
  • Loading branch information
sorrycc committed Mar 9, 2020
1 parent b3069fb commit ba98c2b
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 34 deletions.
Expand Up @@ -17,10 +17,10 @@ describe('createMiddleware', () => {
});
};
const HOME_PAGE = 'homepage';
let watcher = null;
let port;
let server;
let hostname;
let watcher: any = null;
let port: number;
let server: any;
let hostname: string;

beforeAll(async () => {
const service = new Service({
Expand Down
17 changes: 5 additions & 12 deletions packages/preset-built-in/src/plugins/commands/dev/mock/mock.ts
Expand Up @@ -41,19 +41,12 @@ export default function(api: IApi) {

const ignore = userConfig?.mock?.exclude;

// get all mock paths
const mockResult = getMockData({
cwd,
ignore,
registerBabel,
});

// disable when not exist mock dir
if (!mockResult) {
return;
}

api.addBeforeMiddewares(() => {
const mockResult = getMockData({
cwd,
ignore,
registerBabel,
});
const { middleware } = createMiddleware({
...mockResult,
updateMockData: () => {
Expand Down
Expand Up @@ -21,7 +21,6 @@ describe('umi-mock:getMockData', () => {

const { mockData } = getMockData({
cwd: `${fixtures}/normal`,
paths: service.paths,
});
expect(mockData.length).toEqual(2);
});
Expand All @@ -45,8 +44,8 @@ describe('umi-mock:getMockData', () => {
'normal/mock/_c.js',
'normal/mock/a.js',
'normal/mock/b.js',
// 'normal/pages/a/_mock.js',
// 'normal/pages/b/_mock.js',
'normal/pages/a/_mock.js',
'normal/pages/b/_mock.js',
]);
});

Expand Down
27 changes: 12 additions & 15 deletions packages/preset-built-in/src/plugins/commands/dev/mock/utils.ts
Expand Up @@ -43,27 +43,24 @@ export interface IGetMockDataResult {
*
* @param param
*/
export const getMockData: (
opts: IGetMockPaths,
) => IGetMockDataResult | null = ({
export const getMockData: (opts: IGetMockPaths) => IGetMockDataResult = ({
cwd,
ignore = [],
registerBabel = () => {},
}) => {
const absMockPaths = glob.sync(join(cwd, 'mock/**/*.[jt]s'), {
ignore,
});
if (!absMockPaths.length) {
return null;
}
const absConfigPath = join(cwd, '.umirc.mock.js');
const absConfigPathWithTS = join(cwd, '.umirc.mock.ts');

const mockPaths = [
...(absMockPaths || []),
absConfigPath,
absConfigPathWithTS,
...(glob.sync('mock/**/*.[jt]s', {
cwd,
ignore,
}) || []),
...(glob.sync('**/_mock.[jt]s', {
cwd,
ignore,
}) || []),
'.umirc.mock.js',
'.umirc.mock.ts',
]
.map(path => join(cwd, path))
.filter(path => path && existsSync(path))
.map(path => winPath(path));

Expand Down

0 comments on commit ba98c2b

Please sign in to comment.