Skip to content

Commit

Permalink
feat: write files to report
Browse files Browse the repository at this point in the history
  • Loading branch information
AriPerkkio committed Mar 21, 2022
1 parent 942c1eb commit 12cd4db
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 18 deletions.
12 changes: 8 additions & 4 deletions src/sonar-reporter.ts
@@ -1,7 +1,7 @@
import { existsSync, mkdirSync, rmSync, writeFileSync } from 'fs';
import { dirname, resolve } from 'pathe';

import type { Reporter, Vitest } from './types';
import type { File, Reporter, Vitest } from './types';

export default class SonarReporter implements Reporter {
ctx!: Vitest;
Expand All @@ -20,7 +20,7 @@ export default class SonarReporter implements Reporter {
}
}

onFinished() {
onFinished(files?: File[]) {
const reportFile = resolve(
this.ctx.config.root,
this.ctx.config.outputFile
Expand All @@ -31,14 +31,18 @@ export default class SonarReporter implements Reporter {
mkdirSync(outputDirectory, { recursive: true });
}

writeFileSync(reportFile, generateXml(), 'utf-8');
writeFileSync(reportFile, generateXml(files), 'utf-8');
this.ctx.log(`SonarQube report written to ${reportFile}`);
}
}

function generateXml() {
function generateXml(files?: File[]) {
// prettier-ignore
return `
<testExecutions version="1">
${files?.map((file) => `
<file path="${file.name}">
</file>`.trim())}
</testExecutions>
`.trim();
}
18 changes: 5 additions & 13 deletions src/types.ts
Expand Up @@ -5,18 +5,10 @@ import type { defineConfig } from 'vitest/config';
*/
type UserConfig = Parameters<typeof defineConfig>[0];
type Reporters = NonNullable<UserConfig['test']>['reporters'];
export type Reporter = NonNullable<
Exclude<
Reporters,
| 'default'
| 'verbose'
| 'dot'
| 'json'
| 'tap'
| 'tap-flat'
| 'junit'
| any[]
>
>;
export type Reporter = NonNullable<Exclude<Reporters, string | any[]>>;

type OnInit = NonNullable<Reporter['onInit']>;
export type Vitest = Parameters<OnInit>[0];

type OnFinished = NonNullable<Reporter['onFinished']>;
export type File = NonNullable<Parameters<OnFinished>[0]>[number];
6 changes: 5 additions & 1 deletion test/index.test.ts
Expand Up @@ -10,11 +10,15 @@ beforeEach(cleanup);
test('writes a report', () => {
expect(existsSync(outputFile)).toBe(false);

execSync('yarn test --config test/vite.test-config.ts');
execSync('yarn test --config test/vite.test-config.ts', {
stdio: 'inherit',
});

expect(existsSync(outputFile)).toBe(true);
expect(readFileSync(outputFile, 'utf-8')).toMatchInlineSnapshot(`
"<testExecutions version=\\"1\\">
<file path=\\"test/fixtures/math.test.ts\\">
</file>
</testExecutions>"
`);
});
Expand Down

0 comments on commit 12cd4db

Please sign in to comment.