CodeSampleX

Exemple

babel-plugin-jest-hoist 29.6.3: hoist jest mock calls above import statements using babel-plugin-jest-hoist

Échantillon vérifié pour npm babel-plugin-jest-hoist 29.6.3: hoist jest mock calls above import statements using babel-plugin-jest-hoist. Le contrat s'est…

sha256:2a500d8ff7112502293d05d37d7d5d7221319b1f0863a80b371f3c68073f11f2

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

Cas

HOW
Objectif
hoist jest mock calls above import statements using babel-plugin-jest-hoist
Paquets
Symboles
  • babel-plugin-jest-hoist
Créé
2026-08-27T12:42:00Z

Contrat

  1. plugin exports a default factory function returning pre, visitor, and post lifecycle hooks
  2. pre hook initializes declareJestObjGetterIdentifier on plugin context to inject getter helper
  3. visitor identifies and transforms jest.mock call expressions to use the injected getter
  4. visitor rejects non-function second argument in jest.mock with TypeError
  5. visitor rejects out-of-scope variable access in jest.mock module factory with ReferenceError
  6. visitor permits identifiers with mock prefix within jest.mock module factory
  7. visitor supports hoistable jest.unmock calls with a single string literal argument
  8. post hook hoists marked jest calls and variable declarations to the top of the block statement

Fichiers

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • test/contract.mjs

Télécharger l’artefact source (tar.gz)

Code source

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: hoist jest mock calls above import statements using babel-plugin-jest-hoist
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/babel-plugin-jest-hoist@29.6.3
Demonstrate these symbols/APIs:
  - babel-plugin-jest-hoist

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:ff94b289490de3e88ca0099b408a8a418983003fbced136f6a3c305c9a178aa1","contract":["plugin exports a default factory function returning pre, visitor, and post lifecycle hooks","pre hook initializes declareJestObjGetterIdentifier on plugin context to inject getter helper","visitor identifies and transforms jest.mock call expressions to use the injected getter","visitor rejects non-function second argument in jest.mock with TypeError","visitor rejects out-of-scope variable access in jest.mock module factory with ReferenceError","visitor permits identifiers with mock prefix within jest.mock module factory","visitor supports hoistable jest.unmock calls with a single string literal argument","post hook hoists marked jest calls and variable declarations to the top of the block statement"],"goal":"hoist jest mock calls above import statements using babel-plugin-jest-hoist","kind":"HOW","packages":["pkg:npm/babel-plugin-jest-hoist@29.6.3"],"schemaVersion":1,"symbols":["babel-plugin-jest-hoist"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/babel-plugin-jest-hoist@29.6.3"],"schemaVersion":1,"subject":"pkg:npm/babel-plugin-jest-hoist@29.6.3","symbols":["babel-plugin-jest-hoist"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-babel-plugin-jest-hoist",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-babel-plugin-jest-hoist",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "babel-plugin-jest-hoist": "29.6.3"
      }
    },
    "node_modules/@babel/code-frame": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
      "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
      "license": "MIT",
      "dependencies": {
        "@babel/helper-validator-identifier": "^7.29.7",
        "js-tokens": "^4.0.0",
        "picocolors": "^1.1.1"
      },
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/@babel/helper-string-parser": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
      "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
      "license": "MIT",
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/@babel/helper-validator-identifier": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
      "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
      "license": "MIT",
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/@babel/parser": {
      "version": "7.29.8",
      "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz",
      "integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==",
      "license": "MIT",
      "dependencies": {
        "@babel/types": "^7.29.8"
      },
      "bin": {
        "parser": "bin/babel-parser.js"
      },
      "engines": {
        "node": ">=6.0.0"
      }
    },
    "node_modules/@babel/template": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
      "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",
      "license": "MIT",
      "dependencies": {
        "@babel/code-frame": "^7.29.7",
        "@babel/parser": "^7.29.7",
        "@babel/types": "^7.29.7"
      },
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/@babel/types": {
      "version": "7.29.8",
      "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
      "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
      "license": "MIT",
      "dependencies": {
        "@babel/helper-string-parser": "^7.29.7",
        "@babel/helper-validator-identifier": "^7.29.7"
      },
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/@types/babel__core": {
      "version": "7.20.5",
      "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
      "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==",
      "license": "MIT",
      "dependencies": {
        "@babel/parser": "^7.20.7",
        "@babel/types": "^7.20.7",
        "@types/babel__generator": "*",
        "@types/babel__template": "*",
        "@types/babel__traverse": "*"
      }
    },
    "node_modules/@types/babel__generator": {
      "version": "7.27.0",
      "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz",
      "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==",
      "license": "MIT",
      "dependencies": {
        "@babel/types": "^7.0.0"
      }
    },
    "node_modules/@types/babel__template": {
      "version": "7.4.4",
      "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz",
      "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==",
      "license": "MIT",
      "dependencies": {
        "@babel/parser": "^7.1.0",
        "@babel/types": "^7.0.0"
      }
    },
    "node_modules/@types/babel__traverse": {
      "version": "7.28.0",
      "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz",
      "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==",
      "license": "MIT",
      "dependencies": {
        "@babel/types": "^7.28.2"
      }
    },
    "node_modules/babel-plugin-jest-hoist": {
      "version": "29.6.3",
      "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz",
      "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==",
      "license": "MIT",
      "dependencies": {
        "@babel/template": "^7.3.3",
        "@babel/types": "^7.3.3",
        "@types/babel__core": "^7.1.14",
        "@types/babel__traverse": "^7.0.6"
      },
      "engines": {
        "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
      }
    },
    "node_modules/js-tokens": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
      "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
      "license": "MIT"
    },
    "node_modules/picocolors": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
      "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
      "license": "ISC"
    }
  }
}
package.json
{
  "name": "sample-babel-plugin-jest-hoist",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "babel-plugin-jest-hoist": "29.6.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "hoist jest mock calls above import statements using babel-plugin-jest-hoist",
  "kind": "HOW",
  "packages": [
    "pkg:npm/babel-plugin-jest-hoist@29.6.3"
  ],
  "symbols": [
    "babel-plugin-jest-hoist"
  ]
}
src/index.mjs
import jestHoistModule from "babel-plugin-jest-hoist";

export const jestHoist =
  typeof jestHoistModule === "function"
    ? jestHoistModule
    : jestHoistModule.default || jestHoistModule;

export function createPluginInstance() {
  return jestHoist();
}

export function createMockProgramPath(getterName = "_getJestObj") {
  const unshifted = [];
  const path = {
    scope: {
      generateUidIdentifier(name) {
        return { type: "Identifier", name: getterName };
      }
    },
    unshiftContainer(key, items) {
      unshifted.push({ key, items });
    }
  };
  return { path, unshifted };
}

export function createMockExpressionStatement({
  method = "mock",
  args = [],
  scopeBindings = {},
  parentBindings = {},
  isGlobalBinding = false
} = {}) {
  const replacedNodes = [];
  const parentScope = {
    bindings: parentBindings,
    hasGlobal: (name) => (typeof isGlobalBinding === "function" ? isGlobalBinding(name) : Boolean(isGlobalBinding))
  };
  const innerScope = {
    bindings: scopeBindings,
    parent: parentScope,
    hasGlobal: (name) => parentScope.hasGlobal(name)
  };

  const parsedArgs = args.map((arg) => {
    if (typeof arg === "string") {
      return {
        isStringLiteral: () => true,
        isLiteral: () => true,
        node: { type: "StringLiteral", value: arg }
      };
    }
    if (arg && typeof arg === "object" && arg.isStringLiteral) {
      return arg;
    }
    if (arg && typeof arg === "object" && arg.isFunction) {
      return {
        isFunction: () => true,
        parentPath: { scope: parentScope },
        traverse(visitor, state) {
          if (Array.isArray(arg.referencedIdentifiers)) {
            for (const idName of arg.referencedIdentifiers) {
              state.ids.add({
                node: { type: "Identifier", name: idName },
                scope: innerScope,
                buildCodeFrameError(msg, errType) {
                  return new errType(msg);
                }
              });
            }
          }
        },
        buildCodeFrameError(msg, errType) {
          return new errType(msg);
        }
      };
    }
    return {
      isFunction: () => false,
      isStringLiteral: () => false,
      isLiteral: () => false,
      buildCodeFrameError(msg, errType) {
        return new errType(msg);
      }
    };
  });

  const exprNode = { type: "CallExpression" };
  const exprStmt = {
    get(key) {
      if (key === "expression") {
        return {
          node: exprNode,
          parentPath: null,
          isCallExpression: () => true,
          get(prop) {
            if (prop === "callee") {
              return {
                isMemberExpression: () => true,
                node: { type: "MemberExpression", computed: false },
                get(memberProp) {
                  if (memberProp === "object") {
                    return {
                      isIdentifier: () => true,
                      node: { type: "Identifier", name: "jest" },
                      scope: { hasBinding: () => false },
                      referencesImport: () => false,
                      replaceWith(newNode) {
                        replacedNodes.push(newNode);
                      }
                    };
                  }
                  if (memberProp === "property") {
                    return { node: { type: "Identifier", name: method } };
                  }
                }
              };
            }
            if (prop === "arguments") {
              return parsedArgs;
            }
          }
        };
      }
    }
  };

  return { exprStmt, replacedNodes, exprNode };
}

export function simulateBlockHoisting(plugin, callNodes = []) {
  const insertedVars = [];
  const insertedCalls = [];
  const removedStatements = [];

  const mockBlock = {
    unshiftContainer(key, items) {
      return [
        {
          remove: () => {},
          insertBefore: (n) => insertedVars.push(n)
        },
        {
          remove: () => {},
          insertBefore: (n) => insertedCalls.push(n)
        }
      ];
    },
    traverse(visitorConfig) {
      for (const callNode of callNodes) {
        const mockStmt = {
          node: { type: "ExpressionStatement", expression: callNode },
          parentPath: {
            isBlock: () => true
          },
          remove: () => {
            removedStatements.push(callNode);
          }
        };
        if (visitorConfig.CallExpression) {
          visitorConfig.CallExpression({
            node: callNode,
            getStatementParent: () => mockStmt
          });
        }
      }
    }
  };

  const mockProgram = {
    unshiftContainer(key, items) {
      return mockBlock.unshiftContainer(key, items);
    },
    traverse(visitorConfig) {
      if (visitorConfig.CallExpression) {
        mockBlock.traverse(visitorConfig);
      }
    }
  };

  plugin.post({ path: mockProgram });
  return { insertedVars, insertedCalls, removedStatements };
}
test/contract.mjs
import assert from "node:assert/strict";
import rawPluginModule from "babel-plugin-jest-hoist";
import {
  jestHoist,
  createPluginInstance,
  createMockProgramPath,
  createMockExpressionStatement,
  simulateBlockHoisting
} from "../src/index.mjs";

const rawPlugin =
  typeof rawPluginModule === "function"
    ? rawPluginModule
    : rawPluginModule.default || rawPluginModule;

// Contract 1: plugin exports a default factory function returning pre, visitor, and post lifecycle hooks
{
  assert.equal(typeof jestHoist, "function");
  assert.equal(typeof rawPlugin, "function");
  const instance = createPluginInstance();
  assert.equal(typeof instance.pre, "function");
  assert.equal(typeof instance.post, "function");
  assert.ok(instance.visitor);
  assert.equal(typeof instance.visitor.ExpressionStatement, "function");
}

// Contract 2: pre hook initializes declareJestObjGetterIdentifier on plugin context to inject getter helper
{
  const plugin = createPluginInstance();
  const context = {};
  const { path: programPath, unshifted } = createMockProgramPath("_customJestGetter");

  plugin.pre.call(context, { path: programPath });
  assert.equal(typeof context.declareJestObjGetterIdentifier, "function");

  const getterId1 = context.declareJestObjGetterIdentifier();
  assert.equal(getterId1.name, "_customJestGetter");
  assert.equal(unshifted.length, 1);
  assert.equal(unshifted[0].key, "body");

  // Subsequent invocations return cached identifier without duplicate AST unshifts
  const getterId2 = context.declareJestObjGetterIdentifier();
  assert.equal(getterId2.name, "_customJestGetter");
  assert.equal(unshifted.length, 1);
}

// Contract 3: visitor identifies and transforms jest.mock call expressions to use the injected getter
{
  const plugin = createPluginInstance();
  const context = {};
  const { path: programPath } = createMockProgramPath("_getJestObj");
  plugin.pre.call(context, { path: programPath });

  const { exprStmt, replacedNodes } = createMockExpressionStatement({
    method: "mock",
    args: ["axios"]
  });

  plugin.visitor.ExpressionStatement.call(context, exprStmt);
  assert.equal(replacedNodes.length, 1);
  assert.equal(replacedNodes[0].type, "CallExpression");
  assert.equal(replacedNodes[0].callee.name, "_getJestObj");
}

// Contract 4: visitor rejects non-function second argument in jest.mock with TypeError
{
  const plugin = createPluginInstance();
  const context = {};
  const { path: programPath } = createMockProgramPath("_getJestObj");
  plugin.pre.call(context, { path: programPath });

  const { exprStmt } = createMockExpressionStatement({
    method: "mock",
    args: ["fs", { isFunction: false }]
  });

  assert.throws(
    () => {
      plugin.visitor.ExpressionStatement.call(context, exprStmt);
    },
    {
      name: "TypeError",
      message: /The second argument of `jest\.mock` must be an inline function/
    }
  );
}

// Contract 5: visitor rejects out-of-scope variable access in jest.mock module factory with ReferenceError
{
  const plugin = createPluginInstance();
  const context = {};
  const { path: programPath } = createMockProgramPath("_getJestObj");
  plugin.pre.call(context, { path: programPath });

  const { exprStmt } = createMockExpressionStatement({
    method: "mock",
    args: [
      "lodash",
      {
        isFunction: true,
        referencedIdentifiers: ["unmockedSecretToken"]
      }
    ],
    isGlobalBinding: false
  });

  assert.throws(
    () => {
      plugin.visitor.ExpressionStatement.call(context, exprStmt);
    },
    {
      name: "ReferenceError",
      message: /The module factory of `jest\.mock\(\)` is not allowed to reference any out-of-scope variables/
    }
  );
}

// Contract 6: visitor permits identifiers with mock prefix within jest.mock module factory
{
  const plugin = createPluginInstance();
  const context = {};
  const { path: programPath } = createMockProgramPath("_getJestObj");
  plugin.pre.call(context, { path: programPath });

  const { exprStmt, replacedNodes } = createMockExpressionStatement({
    method: "mock",
    args: [
      "database",
      {
        isFunction: true,
        referencedIdentifiers: ["mockDbConnection", "MOCK_PORT", "mockHandler"]
      }
    ],
    isGlobalBinding: false
  });

  plugin.visitor.ExpressionStatement.call(context, exprStmt);
  assert.equal(replacedNodes.length, 1);
  assert.equal(replacedNodes[0].callee.name, "_getJestObj");
}

// Contract 7: visitor supports hoistable jest.unmock calls with a single string literal argument
{
  const plugin = createPluginInstance();
  const context = {};
  const { path: programPath } = createMockProgramPath("_getJestObj");
  plugin.pre.call(context, { path: programPath });

  const { exprStmt, replacedNodes } = createMockExpressionStatement({
    method: "unmock",
    args: ["react"]
  });

  plugin.visitor.ExpressionStatement.call(context, exprStmt);
  assert.equal(replacedNodes.length, 1);
  assert.equal(replacedNodes[0].callee.name, "_getJestObj");
}

// Contract 8: post hook hoists marked jest calls and variable declarations to the top of the block statement
{
  const plugin = createPluginInstance();
  const context = {};
  const { path: programPath } = createMockProgramPath("_getJestObj");
  plugin.pre.call(context, { path: programPath });

  const { exprStmt, replacedNodes } = createMockExpressionStatement({
    method: "mock",
    args: ["express"]
  });
  plugin.visitor.ExpressionStatement.call(context, exprStmt);

  const { insertedCalls, removedStatements } = simulateBlockHoisting(plugin, replacedNodes);
  assert.equal(removedStatements.length, 1);
  assert.equal(insertedCalls.length, 1);
  assert.equal(insertedCalls[0].type, "ExpressionStatement");
}

console.log("All babel-plugin-jest-hoist contract tests passed successfully.");

Seeder d'origine

anonyme