疑问
书摘&心得
babel-plugin-tester
借助工具已经很完善了,相当于单纯的字符串比较,结果是否符合:
import pluginTester from 'babel-plugin-tester';
import xxxPlugin from '../xxx-plugin';
pluginTester({
plugin: xxxPlugin,
fixtures: path.join(__dirname, '__fixtures__'), // 保存测试点的地方
tests: {
'case1:xxxxxx': '"hello";', // 输入输出都是同个字符串
'case2:xxxxxx': { // 指定输入输出的字符串
code: 'var hello = "hi";',
output: 'var olleh = "hi";',
},
'case3:xxxxxx': { // 指定输入输出的文件,和真实输出对比
fixture: 'changed.js',
outputFixture: 'changed-output.js',
},
'case4:xxxxxx': { // 指定输入字符串,输出到快照文件中,对比测试
code: `
function sayHi(person) {
return 'Hello ' + person + '!'
}
`,
snapshot: true,
},
},
});
dumi的api-parser单元测试的思想
https://github.com/umijs/dumi/blob/master/packages/preset-dumi/src/api-parser/index.test.ts
测试文件:
具体代码不重要,主要的思想是读取原文件,用待测试函数转换后生成一个结果,比较与预期结果是否符合:
function assertResult(filename, extraProperties?) {
expect(winEOL(JSON.stringify(parser(path.join(rawPath, filename), extraProperties), null, 2))).toEqual(
winEOL(
fs
.readFileSync(path.join(expectPath, `${path.basename(filename, '.tsx')}.json`), 'utf8')
.toString(),
),
);
}
describe('api parser', () => {
it('should parse with skipNodeModules', () => {
assertResult('skipNodeModules.tsx', {
skipNodeModules: true,
});
});
});
源文件skipNodeModules.tsx
// skipNodeModules.tsx
import React from 'react';
import type { Node } from 'unist';
export interface IAextendsNodeProps extends Node {
/**
* extra CSS className for this component
*/
className?: string;
/**
* inline styles
*/
style?: React.CSSProperties;
/**
* component size
* @default small
*/
size: 'small' | 'large';
}
// eslint-disable-next-line react/prefer-stateless-function
class AextendsNode extends React.Component<IAextendsNodeProps> {
render() {
return <>Hello World!</>
}
}
export default AextendsNode;
结果skipNodeModules.json
// skipNodeModules.json
{
"AextendsNode": [
{
"identifier": "className",
"description": "extra CSS className for this component",
"type": "string"
},
{
"identifier": "style",
"description": "inline styles",
"type": "CSSProperties"
},
{
"identifier": "size",
"description": "component size",
"type": "\"small\" | \"large\"",
"default": "small",
"required": true
}
]
}
可以看到编译原理的测试是非常灵活的,借助已有工具库可以完成纯字符串转换的比较,当比较涉及的文件类型、转换思路、转换目标发生改变时,只要按照主要思路进行方案调整即可,在测试的过程中,思路>>>方法。
babel插件单元测试的主要思路就是写一段目标代码,再写一份目标代码,转换后比较结果是否符合预期即可。