-
-
Save cmw9706/8ad3307c904bfaa82d33676842dffc6d to your computer and use it in GitHub Desktop.
Generate ts files from feature files
This file contains 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
const fs = require('fs'); | |
const path = require('path'); | |
const keywords = [ | |
'And', | |
'Given', | |
'Then', | |
'When', | |
'Feature:', | |
'Scenario:', | |
'Scenario Outline:', | |
'Background:', | |
'But', | |
]; | |
const outputDir = path.join(__dirname, 'e2e/features/'); | |
const featureDirectory = path.join(__dirname, 'e2e/features/'); | |
const imports = "import { describe, it } from '@jest/globals' \n \n"; | |
fs.readdir(featureDirectory, (err, files) => { | |
if (err) { | |
console.log(err); | |
throw new Error('An error occured'); | |
} | |
for (let i = 0; i < files.length; i++) { | |
const file = files[i]; | |
console.log(file); | |
if (path.extname(file) === '.feature') { | |
const testName = file.split('.')[0]; | |
const keywordedList = fs | |
.readFileSync(path.join(featureDirectory, file), { encoding: 'utf8' }) | |
.split('\n') | |
.filter(x => x) | |
.map(x => x.trim()); | |
let testTemplate = ''; | |
for (let j = 0; j < keywordedList.length; j++) { | |
const step = keywordedList[j]; | |
const keyword = step.split(' ')[0]; | |
if (keywords.indexOf(keyword) === -1) { | |
throw Error(`Step '${step}' is not valid Gherkin syntax`); | |
} | |
switch (keyword) { | |
case 'Feature:': | |
continue; | |
case 'Scenario:': | |
if (testTemplate.length !== 0) { | |
testTemplate += '}); \n'; | |
} | |
testTemplate += `describe('${step}',()=>{ \n`; | |
break; | |
case 'Then': | |
testTemplate += `it('${step}',async()=>{ throw new Error('Not implemented'); }); \n`; | |
break; | |
case 'Given': | |
case 'When': | |
case 'And': | |
case 'But': | |
testTemplate += `it('${step}',async()=>{}); \n`; | |
break; | |
} | |
} | |
testTemplate += '});'; | |
testTemplate = [imports, testTemplate].join(''); | |
const testFileOutput = `${outputDir}/${testName}.test.ts`; | |
if (!fs.existsSync(testFileOutput)) { | |
fs.writeFile(testFileOutput, testTemplate, error => { | |
if (error) { | |
console.error('failed to create test files', error); | |
return; | |
} | |
}); | |
} | |
} | |
} | |
console.log('Test files generated 🧪 ✅'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment