(exports: Export[], importFrom: string, to: vscode.Uri, isRouteFile: boolean)
| 123 | }; |
| 124 | |
| 125 | export const generateTestFile = async (exports: Export[], importFrom: string, to: vscode.Uri, isRouteFile: boolean) => { |
| 126 | if (!exports.length) { |
| 127 | return; |
| 128 | } |
| 129 | |
| 130 | let existingContent = await tryReadFile(to.path); |
| 131 | |
| 132 | const testFileContent = generateTestFileContent(exports, isRouteFile); |
| 133 | // Creates the dependencies to import, eg. default as TestRoute, utilFunction, etc... |
| 134 | const exportsToImport = exports |
| 135 | .map((toImport) => (toImport.isDefault ? `default as ${toImport.name}` : toImport.name)) |
| 136 | .join(", "); |
| 137 | |
| 138 | // File already exists, append stuff to it |
| 139 | if (existingContent) { |
| 140 | const fileName = to.path.split("/").pop(); |
| 141 | // We want to match an existing import partially so we just need the name of the file, eg ../module.name.test.tsx => module.name |
| 142 | const importStatement = `${fileName!.replace(".test.tsx", "").replace(".test.ts", "")}`; |
| 143 | // Adds the imports to the existing import statement |
| 144 | existingContent = addImportsToImportStatement(importStatement, exportsToImport, existingContent); |
| 145 | // Adds import { render } from "@testing-library/react" if it doesn't exist and is needed |
| 146 | const additionalImports = isRouteFile && !existingContent.includes(renderImport) ? `${renderImport};\n` : ""; |
| 147 | // Appends the new test suites to the end of the file and writes back the existing content with modified imports |
| 148 | await vscode.workspace.fs.writeFile(to, Buffer.from(additionalImports + existingContent + "\n" + testFileContent)); |
| 149 | // Formats file |
| 150 | return await formatFile(to.path); |
| 151 | } |
| 152 | // Creating a new file, add the imports and the test suites |
| 153 | const importStatement = `${importFrom.replace(".tsx", "").replace(".ts", "")}`; |
| 154 | const dependencies = `import { ${exportsToImport} } from "${importStatement}";${ |
| 155 | isRouteFile && exports.some((exp) => exp.isDefault || exp.name === "ErrorBoundary") ? `\n${renderImport};\n` : "" |
| 156 | }\n\n`; |
| 157 | await vscode.workspace.fs.writeFile(to, Buffer.from(dependencies + testFileContent)); |
| 158 | await formatFile(to.path); |
| 159 | }; |
no test coverage detected