Best JavaScript code snippet using stryker-parent
instrumenter.spec.ts
Source:instrumenter.spec.ts
1import { expect } from 'chai';2import sinon from 'sinon';3import { testInjector } from '@stryker-mutator/test-helpers';4import { I } from '@stryker-mutator/util';5import { File, Instrumenter } from '../../src/index.js';6import * as parsers from '../../src/parsers/index.js';7import * as transformers from '../../src/transformers/index.js';8import * as printers from '../../src/printers/index.js';9import { createJSAst, createTSAst, createMutable, createInstrumenterOptions } from '../helpers/factories.js';10import { parseJS } from '../helpers/syntax-test-helpers.js';11import { instrumenterTokens } from '../../src/instrumenter-tokens.js';12describe(Instrumenter.name, () => {13 let sut: Instrumenter;14 class Helper {15 public parserStub = sinon.stub();16 public transformerStub: sinon.SinonStubbedMember<typeof transformers.transform> = sinon.stub();17 public printerStub: sinon.SinonStubbedMember<typeof printers.print> = sinon.stub();18 public createParserStub: sinon.SinonStubbedMember<typeof parsers.createParser> = sinon.stub();19 constructor() {20 this.createParserStub.returns(this.parserStub);21 }22 }23 let helper: Helper;24 beforeEach(() => {25 helper = new Helper();26 sut = testInjector.injector27 .provideValue(instrumenterTokens.createParser, helper.createParserStub)28 .provideValue(instrumenterTokens.print, helper.printerStub)29 .provideValue(instrumenterTokens.transform, helper.transformerStub)30 .injectClass(Instrumenter);31 });32 async function act(input: readonly File[], options = createInstrumenterOptions()) {33 return await sut.instrument(input, options);34 }35 it('should parse, transform and print each file', async () => {36 // Arrange37 const { input, output } = arrangeTwoFiles();38 // Act39 const actualResult = await act(input);40 // Assert41 const expectedFiles: File[] = [42 { name: 'foo.js', content: output[0], mutate: true },43 { name: 'bar.ts', content: output[1], mutate: true },44 ];45 expect(actualResult.files).deep.eq(expectedFiles);46 });47 it('should convert line numbers to be 1-based (for babel internals)', async () => {48 // Arrange49 const { input } = arrangeTwoFiles();50 input[0].mutate = [{ start: { line: 0, column: 0 }, end: { line: 6, column: 42 } }];51 // Act52 await act(input);53 // Assert54 const actual = helper.transformerStub.getCall(0).args[2];55 const expected: transformers.TransformerOptions = createInstrumenterOptions({56 excludedMutations: [],57 });58 expect(actual).deep.eq({ options: expected, mutateDescription: [{ start: { line: 1, column: 0 }, end: { line: 7, column: 42 } }] });59 });60 it('should log about instrumenting', async () => {61 await act([62 { name: 'b.js', content: 'foo', mutate: true },63 { name: 'a.js', content: 'bar', mutate: true },64 ]);65 expect(testInjector.logger.debug).calledWith('Instrumenting %d source files with mutants', 2);66 });67 it('should log about the result', async () => {68 helper.transformerStub.callsFake((_, collector: I<transformers.MutantCollector>) => {69 collector.collect('foo.js', parseJS('bar').program.body[0], createMutable());70 });71 await act([72 { name: 'b.js', content: 'foo', mutate: true },73 { name: 'a.js', content: 'bar', mutate: true },74 ]);75 expect(testInjector.logger.info).calledWith('Instrumented %d source file(s) with %d mutant(s)', 2, 2);76 });77 it('should log between each file', async () => {78 // Arrange79 testInjector.logger.isDebugEnabled.returns(true);80 const { input, asts } = arrangeTwoFiles();81 const fakeTransform: typeof transformers.transform = (ast, collector) => {82 if (ast === asts[0]) {83 collector.collect('foo.js', parseJS('bar').program.body[0], createMutable());84 }85 if (ast === asts[1]) {86 collector.collect('foo.js', parseJS('bar').program.body[0], createMutable());87 collector.collect('foo.js', parseJS('bar').program.body[0], createMutable());88 }89 };90 helper.transformerStub.callsFake(fakeTransform);91 // Act92 await act(input);93 // Assert94 expect(testInjector.logger.debug).calledWith('Instrumented foo.js (1 mutant(s))');95 expect(testInjector.logger.debug).calledWith('Instrumented bar.ts (2 mutant(s))');96 });97 function arrangeTwoFiles() {98 const input: File[] = [99 { name: 'foo.js', content: 'foo', mutate: true },100 { name: 'bar.ts', content: 'bar', mutate: true },101 ];102 const asts = [createJSAst(), createTSAst()];103 const output = ['instrumented js', 'instrumented ts'];104 helper.parserStub.withArgs(input[0].content).resolves(asts[0]).withArgs(input[1].content).resolves(asts[1]);105 helper.printerStub.withArgs(asts[0]).returns(output[0]).withArgs(asts[1]).returns(output[1]);106 return { input, asts, output };107 }...
instrumenter.ts
Source:instrumenter.ts
1import path from 'path';2import { tokens, commonTokens } from '@stryker-mutator/api/plugin';3import { Logger } from '@stryker-mutator/api/logging';4import { MutateDescription } from '@stryker-mutator/api/core';5import { createParser } from './parsers/index.js';6import { transform, MutantCollector } from './transformers/index.js';7import { print } from './printers/index.js';8import { InstrumentResult } from './instrument-result.js';9import { InstrumenterOptions } from './instrumenter-options.js';10import { instrumenterTokens } from './instrumenter-tokens.js';11import { File } from './file.js';12/**13 * The instrumenter is responsible for14 * * Generating mutants based on source files15 * * Instrumenting the source code with the mutants placed in `mutant switches`.16 * * Adding mutant coverage expressions in the source code.17 * @see https://github.com/stryker-mutator/stryker-js/issues/151418 */19export class Instrumenter {20 public static inject = tokens(commonTokens.logger, instrumenterTokens.createParser, instrumenterTokens.print, instrumenterTokens.transform);21 constructor(22 private readonly logger: Logger,23 private readonly _createParser = createParser,24 private readonly _print = print,25 private readonly _transform = transform26 ) {}27 public async instrument(files: readonly File[], options: InstrumenterOptions): Promise<InstrumentResult> {28 this.logger.debug('Instrumenting %d source files with mutants', files.length);29 const mutantCollector = new MutantCollector();30 const outFiles: File[] = [];31 let mutantCount = 0;32 const parse = this._createParser(options);33 for await (const { name, mutate, content } of files) {34 const ast = await parse(content, name);35 this._transform(ast, mutantCollector, { options, mutateDescription: toBabelLineNumber(mutate) });36 const mutatedContent = this._print(ast);37 outFiles.push({38 name,39 mutate,40 content: mutatedContent,41 });42 if (this.logger.isDebugEnabled()) {43 const nrOfMutantsInFile = mutantCollector.mutants.length - mutantCount;44 mutantCount = mutantCollector.mutants.length;45 this.logger.debug(`Instrumented ${path.relative(process.cwd(), name)} (${nrOfMutantsInFile} mutant(s))`);46 }47 }48 const mutants = mutantCollector.mutants.map((mutant) => mutant.toApiMutant());49 this.logger.info('Instrumented %d source file(s) with %d mutant(s)', files.length, mutants.length);50 return {51 files: outFiles,52 mutants,53 };54 }55}56function toBabelLineNumber(range: MutateDescription): MutateDescription {57 if (typeof range === 'boolean') {58 return range;59 } else {60 return range.map(({ start, end }) => ({61 start: {62 column: start.column,63 line: start.line + 1,64 },65 end: {66 column: end.column,67 line: end.line + 1,68 },69 }));70 }...
create-instrumenter.ts
Source:create-instrumenter.ts
1import { BaseContext, commonTokens, Injector, tokens } from '@stryker-mutator/api/plugin';2import { instrumenterTokens } from './instrumenter-tokens.js';3import { createParser } from './parsers/index.js';4import { print } from './printers/index.js';5import { transform } from './transformers/index.js';6import { Instrumenter } from './index.js';7export interface InstrumenterContext extends BaseContext {8 [instrumenterTokens.createParser]: typeof createParser;9 [instrumenterTokens.print]: typeof print;10 [instrumenterTokens.transform]: typeof transform;11}12createInstrumenter.inject = tokens(commonTokens.injector);13export function createInstrumenter(injector: Injector<BaseContext>): Instrumenter {14 return injector15 .provideValue(instrumenterTokens.print, print)16 .provideValue(instrumenterTokens.createParser, createParser)17 .provideValue(instrumenterTokens.transform, transform)18 .injectClass(Instrumenter);...
Using AI Code Generation
1const Stryker = require('stryker-parent');2const path = require('path');3const stryker = new Stryker({4 files: [path.resolve(__dirname, 'src/**/*.js')],5 mutate: [path.resolve(__dirname, 'src/**/*.js')],6 mochaOptions: {7 files: [path.resolve(__dirname, 'test/**/*.js')]8 }9});10stryker.instrumenterTokens().then(tokens => {11 console.log(tokens);12});13module.exports = function(config) {14 config.set({15 mochaOptions: {16 }17 });18};19const Stryker = require('stryker-parent');20const path = require('path');21const stryker = new Stryker({22 files: [path.resolve(__dirname, 'src/**/*.js')],23 mutate: [path.resolve(__dirname, 'src/**/*.js')],24 mochaOptions: {25 files: [path.resolve(__dirname, 'test/**/*.js')]26 }27});28stryker.instrumenterTokens().then(tokens => {29 console.log(tokens);30});31module.exports = function(config) {32 config.set({
Using AI Code Generation
1var instrumenter = require('stryker-parent').instrumenterTokens;2var code = 'function add(a, b) { return a + b; }';3var mutatedCode = instrumenter(code);4console.log(mutatedCode);5var instrumenter = require('stryker').instrumenterTokens;6var code = 'function add(a, b) { return a + b; }';7var mutatedCode = instrumenter(code);8console.log(mutatedCode);9var instrumenter = require('stryker-api').instrumenterTokens;10var code = 'function add(a, b) { return a + b; }';11var mutatedCode = instrumenter(code);12console.log(mutatedCode);13var instrumenter = require('stryker').instrumenterTokens;14var code = 'function add(a, b) { return a + b; }';15var mutatedCode = instrumenter(code);16console.log(mutatedCode);17var instrumenter = require('stryker-api').instrumenterTokens;18var code = 'function add(a, b) { return a + b; }';19var mutatedCode = instrumenter(code);20console.log(mutatedCode);21var instrumenter = require('stryker').instrumenterTokens;22var code = 'function add(a, b) { return a + b; }';23var mutatedCode = instrumenter(code);24console.log(mutatedCode);25var instrumenter = require('stryker-api').instrumenterTokens;26var code = 'function add(a, b) { return a + b; }';27var mutatedCode = instrumenter(code);28console.log(mutatedCode);29var instrumenter = require('stryker').instrumenterTokens;30var code = 'function add(a, b) { return a + b; }';31var mutatedCode = instrumenter(code);32console.log(mutatedCode
Using AI Code Generation
1var instrumenterTokens = require('stryker-parent').instrumenterTokens;2var tokens = instrumenterTokens();3console.log(tokens);4var instrumenterTokens = require('stryker-parent').instrumenterTokens;5var tokens = instrumenterTokens();6console.log(tokens);7var instrumenterTokens = require('stryker-parent').instrumenterTokens;8var tokens = instrumenterTokens();9console.log(tokens);10var instrumenterTokens = require('stryker-parent').instrumenterTokens;11var tokens = instrumenterTokens();12console.log(tokens);13var instrumenterTokens = require('stryker-parent').instrumenterTokens;14var tokens = instrumenterTokens();15console.log(tokens);16var instrumenterTokens = require('stryker-parent').instrumenterTokens;17var tokens = instrumenterTokens();18console.log(tokens);19var instrumenterTokens = require('stryker-parent').instrumenterTokens;20var tokens = instrumenterTokens();21console.log(tokens);22var instrumenterTokens = require('stryker-parent').instrumenterTokens;23var tokens = instrumenterTokens();24console.log(tokens);
Using AI Code Generation
1var instrumenterTokens = require('stryker-parent').instrumenterTokens;2var instrumented = instrumenterTokens('var a = 1;');3console.log(instrumented);4var instrumenterTokens = require('stryker-parent').instrumenterTokens;5var instrumented = instrumenterTokens('var a = 1;');6console.log(instrumented);7var instrumenterTokens = require('stryker-parent').instrumenterTokens;8var instrumented = instrumenterTokens('var a = 1;');9console.log(instrumented);10var instrumenterTokens = require('stryker-parent').instrumenterTokens;11var instrumented = instrumenterTokens('var a = 1;');12console.log(instrumented);13var instrumenterTokens = require('stryker-parent').instrumenterTokens;14var instrumented = instrumenterTokens('var a = 1;');15console.log(instrumented);16var instrumenterTokens = require('stryker-parent').instrumenterTokens;17var instrumented = instrumenterTokens('var a = 1;');18console.log(instrumented);19var instrumenterTokens = require('stryker-parent').instrumenterTokens;20var instrumented = instrumenterTokens('var a = 1;');21console.log(instrumented);
Using AI Code Generation
1var instrumenterTokens = require('stryker-parent').instrumenterTokens;2var tokens = instrumenterTokens('var x = 1;');3module.exports = require('./lib/index');4module.exports.instrumenterTokens = require('./instrumenter').tokens;5var esprima = require('esprima');6var escodegen = require('escodegen');7function tokens(code) {8 return esprima.tokenize(code);9}10module.exports = {11};12exports.tokenize = tokenize;13exports.parse = parse;14exports.Syntax = syntax;15function tokenize(code, options) {16 var i, token, lineNumber, lineStart, comment, comments = [], range, ranges = [], tokens = [], stack = [], curlyStack = [], roundStack = [], squareStack = [], templateStack = [], regexAllowed = {}, context = {17 labelSet: {},18 };19 function scanPunctuator(code, context
Using AI Code Generation
1const { instrumenterTokens } = require('stryker-parent');2const tokens = instrumenterTokens('test.js', 'var x = 1;');3console.log(tokens);4const { parse } = require('@babel/parser');5const { instrumenter } = require('stryker-instrumenter');6function instrumenterTokens(filename, code) {7 const ast = parse(code, { sourceType: 'module' });8 const instrumenterResult = instrumenter.instrument(filename, code, ast);9 return instrumenterResult.tokens;10}11module.exports = {12};
Using AI Code Generation
1const { instrumenterTokens } = require('stryker-parent');2const { instrumentCode } = require('stryker-instrumenter');3const codeToBeTested = 'console.log(\'hello\');';4const testCode = 'console.log(\'world\');';5const instrumentedCode = instrumentCode(codeToBeTested, instrumenterTokens);6const instrumentedTest = instrumentCode(testCode, instrumenterTokens);
Using AI Code Generation
1var instrumenter = require('stryker-parent').instrumenterTokens;2var fs = require('fs');3var instrumentedFile = instrumenter.instrumentSync(fs.readFileSync('src.js', 'utf8'), 'src.js');4fs.writeFileSync('src-instrumented.js', instrumentedFile);5var mocha = require('mocha');6var Mocha = mocha.Mocha;7var mocha = new Mocha();8mocha.addFile('test.js');9mocha.run();10var reporter = require('stryker-parent').reporter;11var fs = require('fs');12var coverageReport = reporter.reportSync(fs.readFileSync('src-instrumented.js', 'utf8'));13fs.writeFileSync('coverage.json', coverageReport);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!