Created
November 21, 2021 17:09
-
-
Save capaj/cadfeca3bd601d3447b0a2df87b6f2b8 to your computer and use it in GitHub Desktop.
generate test on the fly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import path from 'path' | |
import fs from 'fs' | |
const jestSpecTemplate = ({ | |
moduleName, | |
fnName, | |
args | |
}: { | |
moduleName: string | |
fnName: string | |
args: string | |
}): string => ` | |
import {${fnName}} from './${moduleName}' | |
test('generated', () => { | |
expect(${fnName}(${args})).toMatchInlineSnapshot(); | |
}); | |
` | |
let c = 0 | |
export const genTest = (fn: any) => { | |
const p = new Proxy(fn, { | |
apply: function (target, thisArg, argumentsList) { | |
console.log('~ argumentsList', argumentsList) | |
console.log('~ thisArg', thisArg) | |
const returnVal = target.apply(thisArg, argumentsList) | |
console.log('~ returnVal', returnVal) | |
console.warn('GENTEST-START:') | |
const spec = jestSpecTemplate({ | |
moduleName: path.basename(__filename), | |
fnName: fn.name, | |
args: argumentsList | |
.map((arg) => { | |
if (typeof arg === 'object') { | |
return JSON.stringify(arg) | |
} | |
return arg | |
}) | |
.join(', ') | |
}) | |
fs.mkdirSync('./__tests__/generated', { recursive: true }) | |
fs.writeFileSync(`./__tests__/generated/${fn.name}-${c}.test.ts`, spec) | |
console.warn('GENTEST-END:') | |
return returnVal | |
} | |
}) | |
return p | |
} | |
// function sum(a, b) { | |
// return a + b | |
// } | |
// function extend(a, b) { | |
// return { ...a, ...b } | |
// } | |
// genTest(extend)({ a: 2 }, { b: 3 }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment