Skip to content

Commit 4ec5660

Browse files
committed
refactor(test): 重构外置模板源测试
- 将模板源的安装和移动操作移到 before 事件中 - 优化了模板名称的获取方式 - 调整了 package.json 读取的位置
1 parent bbde8ff commit 4ec5660

File tree

1 file changed

+28
-26
lines changed

1 file changed

+28
-26
lines changed

test/creator.test.ts

+28-26
Original file line numberDiff line numberDiff line change
@@ -327,42 +327,44 @@ it('外置模板源', async () => {
327327
const createViteRoot = path.join(npmRoot, 'node_modules/create-vite');
328328
const templatesRoot = fs.mkdtempSync(path.join(cwd, 'templates-'));
329329
const projectRoot = fs.mkdtempSync(path.join(cwd, 'project-'));
330-
331-
// 安装 create-vite
332-
fse.outputFileSync(
333-
path.join(npmRoot, 'package.json'),
334-
JSON.stringify({
335-
name: 'test-templates',
336-
version: '1.0.0',
337-
}),
338-
);
339-
cp.execSync('npm install [email protected]', { cwd: npmRoot });
340-
341-
// 移动模板文件到模板根目录
342-
const dirs = fse.readdirSync(createViteRoot).filter((name) => name.startsWith('template-'));
343-
const templateName = dirs[0];
344-
345-
for (const dir of dirs) {
346-
fse.moveSync(path.join(createViteRoot, dir), path.join(templatesRoot, dir));
347-
}
348-
349-
// 读取 package.json
350-
const originPkg = fse.readJsonSync(path.join(templatesRoot, templateName, 'package.json')) as {
351-
name: string;
352-
};
353-
vi.spyOn(clackPrompts, 'select').mockResolvedValue(templateName);
330+
let templateName = '';
354331

355332
// 执行创建
356333
const creator = new Creator({
357334
cwd: projectRoot,
358335
templatesRoot: templatesRoot,
359336
});
337+
338+
creator.on('before', async ({ execCommand }) => {
339+
// 安装 create-vite
340+
fse.outputFileSync(
341+
path.join(npmRoot, 'package.json'),
342+
JSON.stringify({
343+
name: 'test-templates',
344+
version: '1.0.0',
345+
}),
346+
);
347+
await execCommand('npm install [email protected]', { cwd: npmRoot });
348+
349+
// 移动模板文件到模板根目录
350+
const dirs = fse.readdirSync(createViteRoot).filter((name) => name.startsWith('template-'));
351+
templateName = dirs[0];
352+
vi.spyOn(clackPrompts, 'select').mockResolvedValue(templateName);
353+
354+
for (const dir of dirs) {
355+
fse.moveSync(path.join(createViteRoot, dir), path.join(templatesRoot, dir));
356+
}
357+
});
358+
360359
await creator.create();
360+
361+
// 验证项目名
362+
const originPkg = fse.readJsonSync(path.join(templatesRoot, templateName, 'package.json')) as {
363+
name: string;
364+
};
361365
const projectPkg = fse.readJsonSync(path.join(projectRoot, 'package.json')) as {
362366
name: string;
363367
};
364-
365-
// 验证项目名
366368
expect(projectPkg.name).toEqual(originPkg.name);
367369
});
368370
});

0 commit comments

Comments
 (0)