CodeSampleX

샘플

jest-mock 29.7.0: fn

검증된 샘플 — npm jest-mock 29.7.0: fn. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: fn creates a mock function that defaults to returning…

sha256:c3118cb3f4faa866d15da3d2999b2e580e5c5b4bdc9b892fd57fe4b4cd66ce39

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-06

케이스

HOW
목표
verify jest-mock.fn in pkg:npm/jest-mock@29.7.0
패키지
심벌
  • jest-mock.fn
환경
node 22.23.2
생성일
2026-09-06T07:53:28Z

컨트랙트

  1. fn creates a mock function that defaults to returning undefined and tracks call count and arguments
  2. fn records mock.calls, mock.results with return type, and mock.contexts for each invocation
  3. mockReturnValue and mockReturnValueOnce configure synchronous return values with once taking precedence
  4. mockResolvedValue and mockResolvedValueOnce return promises resolving to the configured values
  5. mockRejectedValue and mockRejectedValueOnce return promises rejecting with the configured errors
  6. mockImplementation and mockImplementationOnce override mock execution behavior sequentially
  7. mockReturnThis binds the returned value to the execution this context
  8. mockClear clears recorded calls and results while preserving current mock implementation
  9. mockReset clears recorded calls and resets implementation to return undefined
  10. withImplementation temporarily overrides mock implementation for the duration of a callback

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

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: verify jest-mock.fn in pkg:npm/jest-mock@29.7.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/jest-mock@29.7.0
Demonstrate these symbols/APIs:
  - jest-mock.fn

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:3e202a7070bf30aa087035d08a25b597461e31832c7801d94ca31210e7643435","contract":["fn creates a mock function that defaults to returning undefined and tracks call count and arguments","fn records mock.calls, mock.results with return type, and mock.contexts for each invocation","mockReturnValue and mockReturnValueOnce configure synchronous return values with once taking precedence","mockResolvedValue and mockResolvedValueOnce return promises resolving to the configured values","mockRejectedValue and mockRejectedValueOnce return promises rejecting with the configured errors","mockImplementation and mockImplementationOnce override mock execution behavior sequentially","mockReturnThis binds the returned value to the execution this context","mockClear clears recorded calls and results while preserving current mock implementation","mockReset clears recorded calls and resets implementation to return undefined","withImplementation temporarily overrides mock implementation for the duration of a callback"],"goal":"verify jest-mock.fn in pkg:npm/jest-mock@29.7.0","kind":"HOW","packages":["pkg:npm/jest-mock@29.7.0"],"schemaVersion":1,"symbols":["jest-mock.fn"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/jest-mock@29.7.0"],"schemaVersion":1,"subject":"pkg:npm/jest-mock@29.7.0","symbols":["jest-mock.fn"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const jestMock = require('jest-mock');
const { fn } = jestMock;

/**
 * Creates a mock function with an optional implementation.
 * @param {Function} [implementation]
 * @returns {Function}
 */
function createMockFunction(implementation) {
  return fn(implementation);
}

/**
 * Creates an async mock function that resolves to the specified value.
 * @param {*} resolvedValue
 * @returns {Function}
 */
function createAsyncMock(resolvedValue) {
  const mock = fn();
  mock.mockResolvedValue(resolvedValue);
  return mock;
}

/**
 * Creates an async mock function that rejects with the specified reason.
 * @param {*} rejectionReason
 * @returns {Function}
 */
function createRejectingMock(rejectionReason) {
  const mock = fn();
  mock.mockRejectedValue(rejectionReason);
  return mock;
}

/**
 * Creates a mock function configured to return a sequence of values once,
 * then fall back to a default value.
 * @param {Array<*>} sequence
 * @param {*} [defaultValue]
 * @returns {Function}
 */
function createSequenceMock(sequence, defaultValue) {
  const mock = fn();
  if (defaultValue !== undefined) {
    mock.mockReturnValue(defaultValue);
  }
  for (const val of sequence) {
    mock.mockReturnValueOnce(val);
  }
  return mock;
}

/**
 * Creates a mock function that returns its `this` execution context.
 * @returns {Function}
 */
function createChainableMock() {
  const mock = fn();
  mock.mockReturnThis();
  return mock;
}

/**
 * Extracts metadata and call history from a mock function.
 * @param {Function} mockFn
 * @returns {object}
 */
function inspectMock(mockFn) {
  return {
    name: mockFn.getMockName(),
    callCount: mockFn.mock.calls.length,
    calls: [...mockFn.mock.calls],
    results: [...mockFn.mock.results],
    lastCall: mockFn.mock.lastCall
  };
}

module.exports = {
  fn,
  createMockFunction,
  createAsyncMock,
  createRejectingMock,
  createSequenceMock,
  createChainableMock,
  inspectMock
};
package-lock.json
{
  "name": "sample-jest-mock-fn-verify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-jest-mock-fn-verify",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "jest-mock": "29.7.0"
      }
    },
    "node_modules/@jest/schemas": {
      "version": "29.6.3",
      "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz",
      "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==",
      "license": "MIT",
      "dependencies": {
        "@sinclair/typebox": "^0.27.8"
      },
      "engines": {
        "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
      }
    },
    "node_modules/@jest/types": {
      "version": "29.6.3",
      "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz",
      "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==",
      "license": "MIT",
      "dependencies": {
        "@jest/schemas": "^29.6.3",
        "@types/istanbul-lib-coverage": "^2.0.0",
        "@types/istanbul-reports": "^3.0.0",
        "@types/node": "*",
        "@types/yargs": "^17.0.8",
        "chalk": "^4.0.0"
      },
      "engines": {
        "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
      }
    },
    "node_modules/@sinclair/typebox": {
      "version": "0.27.12",
      "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz",
      "integrity": "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==",
      "license": "MIT"
    },
    "node_modules/@types/istanbul-lib-coverage": {
      "version": "2.0.6",
      "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz",
      "integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==",
      "license": "MIT"
    },
    "node_modules/@types/istanbul-lib-report": {
      "version": "3.0.3",
      "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz",
      "integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==",
      "license": "MIT",
      "dependencies": {
        "@types/istanbul-lib-coverage": "*"
      }
    },
    "node_modules/@types/istanbul-reports": {
      "version": "3.0.4",
      "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz",
      "integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==",
      "license": "MIT",
      "dependencies": {
        "@types/istanbul-lib-report": "*"
      }
    },
    "node_modules/@types/node": {
      "version": "26.4.1",
      "resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.1.tgz",
      "integrity": "sha512-k97ENvZWtvA6yqz5/FS6a7duDgOPEeOQOc2iKS/nY6mX6qJUKtLnWzQS+Xj6tXweyj6ZcTAK2Qecetnvi9nCLA==",
      "license": "MIT",
      "dependencies": {
        "undici-types": "~8.3.0"
      }
    },
    "node_modules/@types/yargs": {
      "version": "17.0.35",
      "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz",
      "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==",
      "license": "MIT",
      "dependencies": {
        "@types/yargs-parser": "*"
      }
    },
    "node_modules/@types/yargs-parser": {
      "version": "21.0.3",
      "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz",
      "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==",
      "license": "MIT"
    },
    "node_modules/ansi-styles": {
      "version": "4.3.0",
      "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
      "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
      "license": "MIT",
      "dependencies": {
        "color-convert": "^2.0.1"
      },
      "engines": {
        "node": ">=8"
      },
      "funding": {
        "url": "https://github.com/chalk/ansi-styles?sponsor=1"
      }
    },
    "node_modules/chalk": {
      "version": "4.1.2",
      "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
      "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
      "license": "MIT",
      "dependencies": {
        "ansi-styles": "^4.1.0",
        "supports-color": "^7.1.0"
      },
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/chalk/chalk?sponsor=1"
      }
    },
    "node_modules/ci-info": {
      "version": "3.9.0",
      "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz",
      "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/sibiraj-s"
        }
      ],
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/color-convert": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
      "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
      "license": "MIT",
      "dependencies": {
        "color-name": "~1.1.4"
      },
      "engines": {
        "node": ">=7.0.0"
      }
    },
    "node_modules/color-name": {
      "version": "1.1.4",
      "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
      "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
      "license": "MIT"
    },
    "node_modules/graceful-fs": {
      "version": "4.2.11",
      "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
      "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
      "license": "ISC"
    },
    "node_modules/has-flag": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
      "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/jest-mock": {
      "version": "29.7.0",
      "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz",
      "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==",
      "license": "MIT",
      "dependencies": {
        "@jest/types": "^29.6.3",
        "@types/node": "*",
        "jest-util": "^29.7.0"
      },
      "engines": {
        "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
      }
    },
    "node_modules/jest-util": {
      "version": "29.7.0",
      "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz",
      "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==",
      "license": "MIT",
      "dependencies": {
        "@jest/types": "^29.6.3",
        "@types/node": "*",
        "chalk": "^4.0.0",
        "ci-info": "^3.2.0",
        "graceful-fs": "^4.2.9",
        "picomatch": "^2.2.3"
      },
      "engines": {
        "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
      }
    },
    "node_modules/picomatch": {
      "version": "2.3.2",
      "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
      "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
      "license": "MIT",
      "engines": {
        "node": ">=8.6"
      },
      "funding": {
        "url": "https://github.com/sponsors/jonschlinkert"
      }
    },
    "node_modules/supports-color": {
      "version": "7.2.0",
      "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
      "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
      "license": "MIT",
      "dependencies": {
        "has-flag": "^4.0.0"
      },
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/undici-types": {
      "version": "8.3.0",
      "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
      "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-jest-mock-fn-verify",
  "version": "1.0.0",
  "private": true,
  "description": "verify jest-mock.fn in pkg:npm/jest-mock@29.7.0",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "jest-mock": "29.7.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify jest-mock.fn in pkg:npm/jest-mock@29.7.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jest-mock@29.7.0"
  ],
  "symbols": [
    "jest-mock.fn"
  ]
}
test/contract.js
'use strict';

const assert = require('assert');
const {
  fn,
  createMockFunction,
  createAsyncMock,
  createRejectingMock,
  createSequenceMock,
  createChainableMock,
  inspectMock
} = require('../index.js');

function testDefaultMockBehavior() {
  const mock = fn();
  assert.strictEqual(mock.getMockName(), 'jest.fn()');

  const result = mock('firstArg', 42);
  assert.strictEqual(result, undefined, 'default mock must return undefined');
  assert.strictEqual(mock.mock.calls.length, 1, 'call count must be 1');
  assert.deepStrictEqual(mock.mock.calls[0], ['firstArg', 42]);
  assert.deepStrictEqual(mock.mock.lastCall, ['firstArg', 42]);
}

function testInvocationRecordsAndContext() {
  const contextObj = { scope: 'test-scope' };
  const mock = fn(function (factor) {
    return factor * 10;
  });

  const returnedVal = mock.call(contextObj, 5);
  assert.strictEqual(returnedVal, 50);
  assert.strictEqual(mock.mock.calls.length, 1);
  assert.deepStrictEqual(mock.mock.calls[0], [5]);
  assert.strictEqual(mock.mock.contexts[0], contextObj);
  assert.strictEqual(mock.mock.results.length, 1);
  assert.strictEqual(mock.mock.results[0].type, 'return');
  assert.strictEqual(mock.mock.results[0].value, 50);

  const errorMock = fn(() => {
    throw new Error('intentional failure');
  });

  assert.throws(() => errorMock(), /intentional failure/);
  assert.strictEqual(errorMock.mock.results[0].type, 'throw');
  assert.strictEqual(errorMock.mock.results[0].value.message, 'intentional failure');
}

function testReturnValuesConfiguration() {
  const mock = fn();
  mock.mockReturnValue('fallback');
  mock.mockReturnValueOnce('one');
  mock.mockReturnValueOnce('two');

  assert.strictEqual(mock(), 'one');
  assert.strictEqual(mock(), 'two');
  assert.strictEqual(mock(), 'fallback');
  assert.strictEqual(mock(), 'fallback');
}

async function testAsyncResolvedValues() {
  const mock = fn();
  mock.mockResolvedValue('default-async');
  mock.mockResolvedValueOnce('first-async');

  const res1 = await mock();
  assert.strictEqual(res1, 'first-async');

  const res2 = await mock();
  assert.strictEqual(res2, 'default-async');

  const helperMock = createAsyncMock('helper-async');
  const helperRes = await helperMock();
  assert.strictEqual(helperRes, 'helper-async');
}

async function testAsyncRejectedValues() {
  const mock = fn();
  mock.mockRejectedValue(new Error('default-async-error'));
  mock.mockRejectedValueOnce(new Error('first-async-error'));

  await assert.rejects(async () => {
    await mock();
  }, {
    name: 'Error',
    message: 'first-async-error'
  });

  await assert.rejects(async () => {
    await mock();
  }, {
    name: 'Error',
    message: 'default-async-error'
  });

  const rejectingHelper = createRejectingMock(new Error('helper-reject'));
  await assert.rejects(async () => {
    await rejectingHelper();
  }, {
    name: 'Error',
    message: 'helper-reject'
  });
}

function testImplementationChaining() {
  const mock = fn(() => 'base');
  mock.mockImplementationOnce(() => 'temp1');
  mock.mockImplementationOnce(() => 'temp2');
  mock.mockImplementation((x) => `custom-${x}`);

  assert.strictEqual(mock('a'), 'temp1');
  assert.strictEqual(mock('b'), 'temp2');
  assert.strictEqual(mock('c'), 'custom-c');
  assert.strictEqual(mock('d'), 'custom-d');
}

function testMockReturnThis() {
  const mock = fn();
  mock.mockReturnThis();

  const receiver = {
    action: mock
  };

  const chained = receiver.action();
  assert.strictEqual(chained, receiver, 'mockReturnThis must return the execution context');

  const helperChain = createChainableMock();
  const host = { chain: helperChain };
  assert.strictEqual(host.chain(), host);
}

function testMockClear() {
  const mock = fn((val) => val * 3);
  assert.strictEqual(mock(4), 12);
  assert.strictEqual(mock.mock.calls.length, 1);
  assert.strictEqual(mock.mock.results.length, 1);

  mock.mockClear();

  assert.strictEqual(mock.mock.calls.length, 0);
  assert.strictEqual(mock.mock.results.length, 0);
  assert.strictEqual(mock.mock.instances.length, 0);
  assert.strictEqual(mock.mock.contexts.length, 0);

  // Implementation remains intact
  assert.strictEqual(mock(5), 15);
  assert.strictEqual(mock.mock.calls.length, 1);
}

function testMockReset() {
  const mock = fn((val) => val * 3);
  assert.strictEqual(mock(4), 12);

  mock.mockReset();

  assert.strictEqual(mock.mock.calls.length, 0);
  assert.strictEqual(mock.mock.results.length, 0);
  // Implementation reset to empty function returning undefined
  assert.strictEqual(mock(5), undefined);
}

function testWithImplementation() {
  const mock = fn(() => 'original');
  let innerResult;

  mock.withImplementation(() => 'override', () => {
    innerResult = mock();
  });

  assert.strictEqual(innerResult, 'override');
  assert.strictEqual(mock(), 'original');
}

function testSequenceAndInspectHelpers() {
  const sequenceMock = createSequenceMock(['alpha', 'beta'], 'omega');
  assert.strictEqual(sequenceMock(), 'alpha');
  assert.strictEqual(sequenceMock(), 'beta');
  assert.strictEqual(sequenceMock(), 'omega');
  assert.strictEqual(sequenceMock(), 'omega');

  const customNamed = createMockFunction();
  customNamed.mockName('inspectedMock');
  customNamed('arg1', 'arg2');

  const stats = inspectMock(customNamed);
  assert.strictEqual(stats.name, 'inspectedMock');
  assert.strictEqual(stats.callCount, 1);
  assert.deepStrictEqual(stats.calls, [['arg1', 'arg2']]);
  assert.deepStrictEqual(stats.lastCall, ['arg1', 'arg2']);
  assert.strictEqual(stats.results[0].type, 'return');
}

async function runAll() {
  testDefaultMockBehavior();
  testInvocationRecordsAndContext();
  testReturnValuesConfiguration();
  await testAsyncResolvedValues();
  await testAsyncRejectedValues();
  testImplementationChaining();
  testMockReturnThis();
  testMockClear();
  testMockReset();
  testWithImplementation();
  testSequenceAndInspectHelpers();

  console.log('Contract tests passed successfully.');
}

runAll().catch((err) => {
  console.error('Contract test failure:', err);
  process.exit(1);
});

오리진 시더

익명