UNPKG

2.25 kBPlain TextView Raw
1import type { JestEnvironment, EnvironmentContext, JestEnvironmentConfig } from '@jest/environment';
2import type { Circus } from '@jest/types';
3import { InstrumenterContext } from '@stryker-mutator/api/core';
4
5import { state } from './messaging.js';
6
7function fullNameDescribeBlock(describe: Circus.DescribeBlock): string {
8 if (describe.parent) {
9 const parentName = fullNameDescribeBlock(describe.parent);
10 return `${parentName} ${describe.name}`.trimStart();
11 } else {
12 return ''; // describe.name === "ROOT_DESCRIBE_BLOCK"
13 }
14}
15
16function fullName(test: Circus.TestEntry): string {
17 const suiteName = fullNameDescribeBlock(test.parent);
18 return `${suiteName} ${test.name}`.trimStart();
19}
20
21const STRYKER_JEST_ENV = Symbol('StrykerJestEnvironment');
22
23export function mixinJestEnvironment<T extends typeof JestEnvironment>(JestEnvironmentClass: T & { [STRYKER_JEST_ENV]?: true }): T {
24 if (JestEnvironmentClass[STRYKER_JEST_ENV]) {
25 return JestEnvironmentClass;
26 } else {
27 class StrykerJestEnvironment extends JestEnvironmentClass {
28 // private readonly strykerFileName: string;
29
30 /**
31 * The shared instrumenter context with the test environment (the `__stryker__` global variable)
32 */
33 private readonly strykerContext: InstrumenterContext;
34
35 public static readonly [STRYKER_JEST_ENV] = true;
36
37 constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {
38 super(config, context);
39 this.strykerContext = this.global[this.global.__strykerGlobalNamespace__] = state.instrumenterContext;
40 state.testFilesWithStrykerEnvironment.add(context.testPath);
41 }
42
43 public handleTestEvent: Circus.EventHandler = async (event: Circus.Event, eventState: Circus.State) => {
44 // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
45 await super.handleTestEvent?.(event as any, eventState);
46 if (state.coverageAnalysis === 'perTest') {
47 if (event.name === 'test_start') {
48 this.strykerContext.currentTestId = fullName(event.test);
49 } else if (event.name === 'test_done') {
50 this.strykerContext.currentTestId = undefined;
51 }
52 }
53 };
54 }
55 return StrykerJestEnvironment;
56 }
57}