├── .nvmrc ├── .husky ├── .gitignore ├── post-merge ├── pre-push ├── post-commit ├── post-rewrite ├── pre-commit └── commit-msg ├── .eslintignore ├── .tool-versions ├── .gitignore ├── .lintstagedrc ├── .bithoundrc ├── commitlint.config.js ├── NOTICE.md ├── rollup.config.mjs ├── .editorconfig ├── .eslintrc.js ├── .github └── workflows │ └── release.yml ├── CONTRIBUTING.md ├── src ├── index.js └── constructors.js ├── package.json ├── README.md ├── test └── index.spec.js └── LICENSE /.nvmrc: -------------------------------------------------------------------------------- 1 | 18 2 | -------------------------------------------------------------------------------- /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | -------------------------------------------------------------------------------- /.tool-versions: -------------------------------------------------------------------------------- 1 | nodejs 22.14.0 2 | 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | .idea/ 3 | dist/ 4 | -------------------------------------------------------------------------------- /.lintstagedrc: -------------------------------------------------------------------------------- 1 | { 2 | "*.js": [ 3 | "eslint --fix" 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /.husky/post-merge: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npm ci 5 | -------------------------------------------------------------------------------- /.husky/pre-push: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npm test 5 | -------------------------------------------------------------------------------- /.husky/post-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | git reset 5 | -------------------------------------------------------------------------------- /.husky/post-rewrite: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npm ci 5 | -------------------------------------------------------------------------------- /.bithoundrc: -------------------------------------------------------------------------------- 1 | { 2 | "critics": { 3 | "lint": {"engine": "standard"} 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npx lint-staged 5 | -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npx commitlint --edit ./.git/COMMIT_EDITMSG 5 | -------------------------------------------------------------------------------- /commitlint.config.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable tree-shaking/no-side-effects-in-initialization */ 2 | module.exports = { extends: ["@commitlint/config-angular"] }; 3 | -------------------------------------------------------------------------------- /NOTICE.md: -------------------------------------------------------------------------------- 1 | ## sinon-helpers 2 | 3 | Copyright 2016-2018 Lukas Taegert-Atkinson 4 | 5 | This product includes software developed at TNG Technology Consulting GmbH (https://www.tngtech.com/). 6 | -------------------------------------------------------------------------------- /rollup.config.mjs: -------------------------------------------------------------------------------- 1 | export default { 2 | input: "src/index.js", 3 | external: ["sinon"], 4 | output: [ 5 | { 6 | file: "dist/index.js", 7 | format: "cjs", 8 | }, 9 | { 10 | file: "dist/index.esm.js", 11 | format: "es", 12 | }, 13 | ], 14 | }; 15 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | insert_final_newline = true 8 | trim_trailing_whitespace = true 9 | max_line_length = 100 10 | indent_style = space 11 | indent_size = 2 12 | 13 | [*.md] 14 | trim_trailing_whitespace = false 15 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line tree-shaking/no-side-effects-in-initialization 2 | module.exports = { 3 | extends: ["plugin:prettier/recommended"], 4 | plugins: ["tree-shaking"], 5 | parserOptions: { 6 | ecmaVersion: 12, 7 | sourceType: "module", 8 | }, 9 | rules: { 10 | "tree-shaking/no-side-effects-in-initialization": 2, 11 | }, 12 | }; 13 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | release: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout Commit 13 | uses: actions/checkout@v4 14 | - name: Setup Node 15 | uses: actions/setup-node@v4 16 | with: 17 | node-version: 22 18 | - name: Install dependencies 19 | run: npm ci --ignore-scripts 20 | - name: Publish 21 | env: 22 | GH_TOKEN: ${{ secrets.GH_TOKEN }} 23 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 24 | run: npm run semantic-release 25 | 26 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | ### You found a bug or something is not working as expected 4 | 5 | - Ideally: File a pull request with a red test! (but take a look at the [Coding Guidelines](#coding-guidelines) first) 6 | - Also nice: File a pull request with a test and a proposed fix :) 7 | - If you can do neither: File an issue outlining the expected behavior, actual behavior, and steps to reproduce the problem. 8 | 9 | ### You have an idea on how to improve the package 10 | 11 | - If you want to show anything by code, or actually want to contribute code, file a pull request. Even if it is not merged, 12 | this pull request makes it easier to discuss the proposed changes. 13 | - Otherwise, please file an issue. 14 | 15 | ### Coding Guidelines 16 | 17 | - Code style must follow the [standard](https://github.com/feross/standard) rules. 18 | - Commit messages must follow the [AngularJS Commit Message Conventions](https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit); 19 | 20 | If you `npm install` before committing anything, both should be enforced automatically. 21 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import sinon from "sinon"; 2 | import /* tree-shaking no-side-effects-when-called */ getStubOrSpyConstructor from "./constructors"; 3 | 4 | const setMethodToStub = (object) => (methodName) => { 5 | if (!(methodName in object)) { 6 | object[methodName] = sinon.stub(); 7 | } 8 | }; 9 | 10 | const spyOnMethod = (object) => (methodName) => { 11 | if ( 12 | !(methodName in Object.prototype) && 13 | !(object[methodName] && object[methodName].isSinonProxy) 14 | ) { 15 | sinon.spy(object, methodName); 16 | } 17 | }; 18 | 19 | const copyAndSpyOnMethod = (object, source) => (methodName) => { 20 | if (source[methodName].isSinonProxy) { 21 | object[methodName] = source[methodName]; 22 | } else { 23 | object[methodName] = sinon.spy(source[methodName]); 24 | } 25 | }; 26 | 27 | const getStubConstructorProperties = (Target) => ({ 28 | SourceConstructor: function () {}, 29 | processMethodOfInstance: setMethodToStub, 30 | getInstanceMethodNameSource: () => Target.prototype, 31 | processMethodOfConstructor: (TheConstructor) => setMethodToStub(TheConstructor), 32 | }); 33 | 34 | const getSpyConstructorProperties = (Target) => ({ 35 | SourceConstructor: Target, 36 | processMethodOfInstance: spyOnMethod, 37 | getInstanceMethodNameSource: (instance) => instance, 38 | processMethodOfConstructor: (TheConstructor) => copyAndSpyOnMethod(TheConstructor, Target), 39 | }); 40 | 41 | export const getStubConstructor = /* @__PURE__ */ getStubOrSpyConstructor( 42 | getStubConstructorProperties, 43 | ); 44 | 45 | export const getSpyConstructor = /* @__PURE__ */ getStubOrSpyConstructor( 46 | getSpyConstructorProperties, 47 | ); 48 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sinon-helpers", 3 | "description": "Create easily configurable sinon stubs that mimic constructors and keep track of their instances", 4 | "author": "Lukas Taegert ", 5 | "license": "Apache-2.0", 6 | "main": "dist/index.js", 7 | "module": "dist/index.esm.js", 8 | "engines": { 9 | "node": ">=10.0.0" 10 | }, 11 | "files": [ 12 | "dist" 13 | ], 14 | "repository": { 15 | "type": "git", 16 | "url": "https://github.com/TNG/sinon-helpers.git" 17 | }, 18 | "keywords": [ 19 | "sinon", 20 | "constructor", 21 | "stub", 22 | "mock", 23 | "spy" 24 | ], 25 | "bugs": { 26 | "url": "https://github.com/TNG/sinon-helpers/issues" 27 | }, 28 | "homepage": "https://github.com/TNG/sinon-helpers#readme", 29 | "peerDependencies": { 30 | "sinon": ">=1.15.0" 31 | }, 32 | "devDependencies": { 33 | "@commitlint/cli": "^19.7.1", 34 | "@commitlint/config-angular": "^19.7.1", 35 | "chai": "^5.2.0", 36 | "eslint": "^8.57.0", 37 | "eslint-config-prettier": "^10.0.1", 38 | "eslint-plugin-import": "^2.31.0", 39 | "eslint-plugin-node": "^11.1.0", 40 | "eslint-plugin-prettier": "^5.2.3", 41 | "eslint-plugin-promise": "^7.2.1", 42 | "eslint-plugin-tree-shaking": "^1.12.2", 43 | "husky": "^9.1.7", 44 | "lint-staged": "^15.4.3", 45 | "mocha": "^11.1.0", 46 | "prettier": "^3.5.1", 47 | "rollup": "^4.34.8", 48 | "semantic-release": "^25.0.2", 49 | "sinon": "^16.1.3" 50 | }, 51 | "scripts": { 52 | "build": "rollup -c", 53 | "test": "npm run build && mocha", 54 | "lint": "eslint --fix *.js src/**/*.js test/**/*.js", 55 | "prepare": "husky install && npm run build", 56 | "semantic-release": "semantic-release" 57 | }, 58 | "version": "0.0.0-development" 59 | } 60 | -------------------------------------------------------------------------------- /src/constructors.js: -------------------------------------------------------------------------------- 1 | const getArrayFromArrayLikeObject = (args) => Array.prototype.slice.call(args); 2 | 3 | const isMethod = (object) => (propName) => 4 | !Object.getOwnPropertyDescriptor(object, propName).get && 5 | typeof object[propName] === "function" && 6 | !(propName === "constructor"); 7 | 8 | const applyToEachFunctionKeyInObject = (appliedFunction, object) => 9 | Object.getOwnPropertyNames(object).filter(isMethod(object)).forEach(appliedFunction); 10 | 11 | const applyToEachFunctionKeyInPrototypeChain = (appliedFunction, object) => { 12 | if (object) { 13 | applyToEachFunctionKeyInObject(appliedFunction, object); 14 | applyToEachFunctionKeyInPrototypeChain(appliedFunction, Object.getPrototypeOf(object)); 15 | } 16 | }; 17 | 18 | const getInstanceIndexWithValidation = (index, numInstances) => { 19 | const instanceIndex = index || 0; 20 | 21 | if (typeof index === "undefined") { 22 | if (numInstances > 1) { 23 | throw new Error( 24 | "Tried to access only instance of StubConstructor, " + 25 | `but there were ${numInstances} instances.`, 26 | ); 27 | } 28 | } 29 | if (numInstances <= instanceIndex) { 30 | throw new Error( 31 | `Tried to access StubConstructor instance ${instanceIndex}, ` + 32 | `but there were only ${numInstances} instances.`, 33 | ); 34 | } 35 | return instanceIndex; 36 | }; 37 | 38 | export default /* tree-shaking no-side-effects-when-called */ (getConstructorProperties) => 39 | (Target) => { 40 | const constructorProps = getConstructorProperties(Target); 41 | let init; 42 | 43 | function StubOrSpyConstructor() { 44 | constructorProps.SourceConstructor.apply(this, arguments); 45 | StubOrSpyConstructor.args.push(getArrayFromArrayLikeObject(arguments)); 46 | if (this instanceof StubOrSpyConstructor) { 47 | StubOrSpyConstructor.instances.push(this); 48 | 49 | Target && 50 | applyToEachFunctionKeyInPrototypeChain( 51 | constructorProps.processMethodOfInstance(this), 52 | constructorProps.getInstanceMethodNameSource(this), 53 | ); 54 | init && init(this); 55 | } else { 56 | StubOrSpyConstructor.instances.push(null); 57 | } 58 | } 59 | 60 | StubOrSpyConstructor.prototype = constructorProps.SourceConstructor.prototype; 61 | 62 | StubOrSpyConstructor.withInit = function (onInit) { 63 | init = onInit; 64 | return this; 65 | }; 66 | 67 | StubOrSpyConstructor.instances = []; 68 | 69 | StubOrSpyConstructor.getInstance = (index) => { 70 | const validatedIndex = getInstanceIndexWithValidation( 71 | index, 72 | StubOrSpyConstructor.instances.length, 73 | ); 74 | return StubOrSpyConstructor.instances[validatedIndex]; 75 | }; 76 | 77 | StubOrSpyConstructor.args = []; 78 | 79 | Target && 80 | applyToEachFunctionKeyInObject( 81 | constructorProps.processMethodOfConstructor(StubOrSpyConstructor), 82 | Target, 83 | ); 84 | return StubOrSpyConstructor; 85 | }; 86 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sinon-helpers 2 | 3 | Create easily configurable [sinon](https://github.com/sinonjs/sinon) stubs that mimic constructors and keep track of their instances. 4 | 5 | [![npm](https://img.shields.io/npm/v/sinon-helpers.svg?maxAge=3600)](https://www.npmjs.com/package/sinon-helpers) 6 | [![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?maxAge=3600)](http://standardjs.com/) 7 | [![npm](https://img.shields.io/npm/dm/sinon-helpers.svg?maxAge=3600)](https://www.npmjs.com/package/sinon-helpers) 8 | [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?maxAge=3600)](https://github.com/semantic-release/semantic-release) 9 | 10 | If updating from v1, please see [updating from v1 to v2](#migrating-from-v1-to-v2). 11 | 12 | ## Motivation 13 | 14 | Especially when working with the new ES6 classes, a common problem in unit testing is to find out if a module creates 15 | instances of a class using the right constructor arguments and which methods are called on these instances. Moreover, 16 | it would be nice to be able to control that these classes are properly stubbed i.e. that in our tests, none of the 17 | original class code is executed. 18 | 19 | New test dependencies can be easily injected with [rewire](https://github.com/jhnns/rewire) or 20 | [proxyquire](https://github.com/thlorenz/proxyquire) for [node](https://nodejs.org) testing and 21 | [inject-loader](https://github.com/plasticine/inject-loader) or 22 | [babel-plugin-rewire](https://github.com/speedskater/babel-plugin-rewire) for [webpack](https://webpack.github.io/) 23 | testing. The question remains how the stated goal can be achieved using a mocking library such as 24 | [sinon](https://github.com/sinonjs/sinon). 25 | 26 | In the examples, we want to mock a constructor `MyConstructor`. 27 | 28 | ### Approaches without `sinon-helpers` 29 | 30 | - Replace `MyConstructor` by `sinon.stub(MyConstructor)`. That way, we can find out which parameters are used to create 31 | instances. The instances, however, will feature none of the methods of `MyConstructor`. 32 | - Do the same using `sinon.spy(MyConstructor)` instead. But now the original code is executed as well and we still 33 | cannot test method invocations. 34 | - To test method invocations, we could stub methods of the prototype i.e. 35 | `sinon.stub(MyConstructor.prototype, 'myMethod')` (do not forget to remove your stub after the test!), or if 36 | `MyConstructorStub = sinon.stub(MyConstructor)`, we could use `MyConstructorStub.prototype.myMethod = sinon.stub()` to 37 | add the corresponding stubs. Now, however, all instances share the same stubs and we cannot match stub invocations with 38 | the instances on which they were invoked. 39 | 40 | To really solve this problem, we will need to create our own custom constructor. **sinon-helpers** is a library that 41 | offers an easy and generic solution to this problem. 42 | 43 | ### What **sinon-helpers** offers 44 | 45 | - `MyStubConstructor = getStubConstructor(MyConstructor)` generates a new constructor using `MyConstrucor` as a template. This means that new instances will contain all methods of `MyConstructor` as stubs including inherited and non-enumerable methods but skipping getters. 46 | - `MyStubConstructor.instances` holds an array of all instances that have been created using this constructor. If you expect only a single instance to be created, you can retrieve it directly via `MyStubConstructor.getInstance()`, which will also throw an error if more than one or no instance has been created. Thus you can test for all instances separately which methods have been invoked in which way. 47 | - `MyStubConstructor.args` returns an array of arrays of arguments used to create the instances. 48 | - As the prototype is not modified, you do not have to clean up your stubs after the test! 49 | 50 | ## Installation 51 | 52 | ```bash 53 | npm install --save-dev sinon-helpers 54 | ``` 55 | 56 | or 57 | 58 | ```bash 59 | yarn add --dev sinon-helpers 60 | ``` 61 | 62 | ## Usage 63 | 64 | ```js 65 | var sh = require('sinon-helpers') // CommonJS 66 | import * as sh from 'sinon-helpers' // ES6 67 | // alternative: import {getStubConstructor, getSpyConstructor} from 'sinon-helpers' 68 | 69 | // Create a constructor mimicking a given constructor 70 | var MyStubConstructor = sh.getStubConstructor(MyConstructor) 71 | 72 | // You can initialize your stub to e.g. provide return values for your methods 73 | // or add fields that are not part of the prototype 74 | var MyStubConstructor = sh.getStubConstructor(MyConstructor).withInit(instance => { 75 | // this assumes MyConstructor.prototype.myMethod exists 76 | instance.myMethod.returns(42) 77 | instance.additionalField = 'added' 78 | }) 79 | 80 | // Create a constructor that calls through to the original constructor 81 | // with spies on all methods instead of stubs 82 | var MySpyConstructor = sh.getSpyConstructor(MyConstructor) 83 | ``` 84 | 85 | ## API 86 | 87 | ### `getStubConstructor()` 88 | 89 | Returns a [`StubConstructor`](#stubconstructor-api) mimicking the given constructor `OriginalConstructor`. When called with `new`, this constructor creates an object with stubs for any methods of the prototype object of `ConstructorName`. 90 | 91 | If you call `getStubConstructor` without any arguments, you receive a StubConstructor without any pre-defined methods. A `StubConstructor` features methods to configure and query the created instances. 92 | 93 | ### `StubConstructor` API 94 | 95 | A `StubConstructor` has the following methods and fields: 96 | 97 | - `.withInit(onInit)` 98 | Each time a new instance is created, `onInit(instance)` is called receiving the new instance as parameter; this enables you to perform manual post-processing like configuring return values and adding additional fields before the instance is returned. 99 | - `.instances` 100 | An array of all instances created with the stub constructor. Contains `null` if the constructor is called without `new`. 101 | - `.getInstance()` 102 | Throws an error if no or more than one instance has been created. Otherwise, returns the instance created. 103 | - `.getInstance(index)` 104 | Throws an error if not at least `index` instances have been created. Otherwise, returns the instance `index`. 105 | - `.args` 106 | An array of arrays containing the arguments of each constructor call. 107 | 108 | ### `getSpyConstructor(OriginalConstructor)` 109 | 110 | Returns a [`SpyConstructor`](#spyconstructor-api) of the given constructor `OriginalConstructor`. A `SpyConstructor` is similar to a `StubConstructor` except for the following differences: 111 | 112 | - The `OriginalConstructor` is called when creating a new instance. 113 | - Methods are not stubbed but spied on. 114 | - Which methods are spied on is not determined by looking at the prototype but by looking at what methods are actually present after the original constructor has run. 115 | 116 | This is useful if you need to preserve the constructor's functionality while being able to track its instances. Note however that having to rely on `SpyConstructor`s instead of `StubConstructor`s may be an indication of strong couplings in your software that are generally a sign that your architecture could be improved. 117 | 118 | ### `SpyConstructor` API 119 | 120 | A `SpyConstructor` has the following methods and fields: 121 | 122 | - `.withInit(onInit)` 123 | When a new instance is created, `onInit(instance)` is called receiving the new instance as parameter; this enables you to perform manual post-processing before the instance is returned. 124 | - `.instances` 125 | An array of all instances created with the spy constructor. Contains `null` if the constructor is called without `new`. 126 | - `.getInstance()` 127 | Throws an error if no or more than one instance has been created. Otherwise, returns the instance created. 128 | - `.getInstance(index)` 129 | Throws an error if not at least `index` instances have been created. Otherwise, returns the instance `index`. 130 | - `.args` 131 | An array of arrays containing the arguments of each constructor call. 132 | 133 | ## Migrating from v1 to v2 134 | 135 | - Instead of `getInstances()`, use `instances` to access the array of instances. 136 | - Instead of `getInstancesArgs()`, use `args` to access the arguments used to create instances. 137 | - `afterCreation()` is now called `withInit()`. 138 | - `withMethods`, `withStubs`: These methods have been removed in favour of using `withInit()`, which is much more powerful. 139 | 140 | ## Contributing 141 | 142 | Feel like this library could do more for you? Found an issue with your setup? Want to get involved? Then why not [contribute](./CONTRIBUTING.md) by raising an issue or creating a pull-request! 143 | -------------------------------------------------------------------------------- /test/index.spec.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | /* eslint-disable no-unused-expressions,no-new,tree-shaking/no-side-effects-in-initialization */ 3 | 4 | const sinonHelpers = require("../dist/index"); 5 | const getStubConstructor = sinonHelpers.getStubConstructor; 6 | const getSpyConstructor = sinonHelpers.getSpyConstructor; 7 | 8 | const expect = require("chai").expect; 9 | const sinon = require("sinon"); 10 | 11 | let TestConstructor; 12 | 13 | beforeEach(function () { 14 | global.sinon = sinon; 15 | 16 | const testPrototype2 = { 17 | proto2: function () { 18 | return "p2"; 19 | }, 20 | field1: function () { 21 | return "pf1"; 22 | }, 23 | }; 24 | 25 | const testPrototype1 = Object.create(testPrototype2, { 26 | proto1: { 27 | writable: true, 28 | enumerable: false, 29 | value: function () { 30 | return "p1"; 31 | }, 32 | }, 33 | }); 34 | 35 | // if this were defined in the object literal, it would be evaluated by Object.create 36 | Object.defineProperty(testPrototype1, "protoGetter", { 37 | get: function () { 38 | throw new Error("inherited getter was evaluated"); 39 | }, 40 | }); 41 | 42 | const testPrototype = Object.create(testPrototype1, { 43 | field1: { 44 | writable: true, 45 | enumerable: true, 46 | value: function () { 47 | return 1; 48 | }, 49 | }, 50 | field2: { 51 | writable: true, 52 | enumerable: false, 53 | value: function () { 54 | return 2; 55 | }, 56 | }, 57 | }); 58 | 59 | TestConstructor = function () { 60 | if (this instanceof TestConstructor) { 61 | this.args = Array.prototype.slice.call(arguments); 62 | this.field3 = function () { 63 | return 3; 64 | }; 65 | this.field4 = sinon.stub(); 66 | Object.defineProperty(this, "getter", { 67 | get: function () { 68 | throw new Error("getter was evaluated"); 69 | }, 70 | }); 71 | } 72 | }; 73 | 74 | TestConstructor.prototype = testPrototype; 75 | TestConstructor.classMethod1 = function () { 76 | return "i1"; 77 | }; 78 | TestConstructor.classMethod2 = sinon.stub(); 79 | }); 80 | 81 | afterEach(function () { 82 | delete global.sinon; 83 | }); 84 | 85 | describe("getStubConstructor", function () { 86 | let StubConstructor; 87 | 88 | beforeEach(function () { 89 | StubConstructor = getStubConstructor(TestConstructor); 90 | }); 91 | 92 | it("should return a constructor that creates an object with all methods of the prototype object", function () { 93 | const stubbedObject = new StubConstructor(); 94 | 95 | expect(stubbedObject.field1).to.be.a("function", "field1"); 96 | expect(stubbedObject.field2).to.be.a("function", "field2"); 97 | expect(stubbedObject.proto1).to.be.a("function", "proto1"); 98 | expect(stubbedObject.proto2).to.be.a("function", "proto2"); 99 | }); 100 | 101 | it("should not call through to the original constructor", function () { 102 | const stubbedObject = new StubConstructor(); 103 | 104 | expect(stubbedObject.field3).to.be.undefined; 105 | }); 106 | 107 | it("should create stubs for all class methods", function () { 108 | expect(StubConstructor.classMethod1).to.have.property("isSinonProxy", true); 109 | expect(StubConstructor.classMethod1()).to.be.undefined; 110 | expect(StubConstructor.classMethod2).to.have.property("isSinonProxy", true); 111 | }); 112 | 113 | it("should create an empty constructor if no arguments are supplied", function () { 114 | StubConstructor = getStubConstructor(); 115 | const stubbedObject = new StubConstructor(); 116 | 117 | expect(stubbedObject).to.be.an("object"); 118 | }); 119 | }); 120 | 121 | describe("getSpyConstructor", function () { 122 | let SpyConstructor; 123 | 124 | beforeEach(function () { 125 | SpyConstructor = getSpyConstructor(TestConstructor); 126 | }); 127 | 128 | it("should return a constructor that creates an object with all methods the constructor creates", function () { 129 | const spiedObject = new SpyConstructor(); 130 | 131 | expect(spiedObject.field1()).to.equal(1); 132 | expect(spiedObject.field2()).to.equal(2); 133 | expect(spiedObject.field3()).to.equal(3); 134 | expect(spiedObject.proto1()).to.equal("p1"); 135 | expect(spiedObject.proto2()).to.equal("p2"); 136 | }); 137 | 138 | it("should create instances of the original constructor", function () { 139 | const spiedObject = new SpyConstructor(); 140 | expect(spiedObject).to.be.an.instanceof(TestConstructor); 141 | }); 142 | 143 | it("should create instances using the right arguments", function () { 144 | const spiedObject = new SpyConstructor("Var 1", 2); 145 | expect(spiedObject.args).to.deep.equal(["Var 1", 2]); 146 | }); 147 | 148 | it("should put spies on all methods", function () { 149 | const spiedObject = new SpyConstructor(); 150 | 151 | expect(spiedObject.field1).to.have.property("isSinonProxy", true, "field1"); 152 | expect(spiedObject.field2).to.have.property("isSinonProxy", true, "field2"); 153 | expect(spiedObject.field3).to.have.property("isSinonProxy", true, "field3"); 154 | expect(spiedObject.field4).to.have.property("isSinonProxy", true, "field4"); 155 | expect(spiedObject.proto1).to.have.property("isSinonProxy", true, "proto1"); 156 | expect(spiedObject.proto2).to.have.property("isSinonProxy", true, "proto2"); 157 | }); 158 | 159 | it("should spy on all class methods", function () { 160 | expect(SpyConstructor.classMethod1).to.have.property("isSinonProxy", true); 161 | expect(SpyConstructor.classMethod1()).to.equal("i1"); 162 | expect(SpyConstructor.classMethod2).to.have.property("isSinonProxy", true); 163 | }); 164 | }); 165 | 166 | describe("getSpy- and getStubConstructor", function () { 167 | const dataProvider = [ 168 | { 169 | description: "getStubConstrucor", 170 | getConstructor: getStubConstructor, 171 | }, 172 | { 173 | description: "getSpyConstrucor", 174 | getConstructor: getSpyConstructor, 175 | }, 176 | ]; 177 | 178 | dataProvider.forEach(function (testData) { 179 | describe(testData.description, function () { 180 | let NewConstructor; 181 | 182 | beforeEach(function () { 183 | NewConstructor = testData.getConstructor(TestConstructor); 184 | }); 185 | 186 | it("should create instances of itself", function () { 187 | const instance = new NewConstructor(); 188 | expect(instance).to.be.an.instanceof(NewConstructor); 189 | }); 190 | 191 | describe("withInit", function () { 192 | it("should allow for manual post-processing before an instance is created", function () { 193 | NewConstructor.withInit(function (instance) { 194 | instance.extraField = 7; 195 | instance.returnSelf = sinon.stub().callsFake(() => instance); 196 | }); 197 | const instance = new NewConstructor(); 198 | expect(instance.extraField).to.equal(7); 199 | expect(instance.returnSelf().returnSelf()).to.equal(instance); 200 | }); 201 | 202 | it("should return the constructor", function () { 203 | expect( 204 | NewConstructor.withInit(function (instance) { 205 | instance.extraField = 7; 206 | }), 207 | ).to.equal(NewConstructor); 208 | }); 209 | }); 210 | 211 | describe("instances", function () { 212 | it("should be an empty list if there are no instances", function () { 213 | expect(NewConstructor.instances).to.deep.equal([]); 214 | }); 215 | 216 | it("should be a list of instances with null for non-constructor calls", function () { 217 | const instance1 = new NewConstructor(); 218 | NewConstructor(); 219 | const instance2 = new NewConstructor(); 220 | 221 | expect(NewConstructor.instances).to.deep.equal([instance1, null, instance2]); 222 | }); 223 | }); 224 | 225 | describe("getInstance", function () { 226 | it("should return a single instance if one has been created", function () { 227 | const instance = new NewConstructor(); 228 | 229 | expect(NewConstructor.getInstance()).to.equal(instance); 230 | }); 231 | 232 | it("should throw an error if no instance has been created", function () { 233 | expect(NewConstructor.getInstance).to.throw(/0 instances/); 234 | }); 235 | 236 | it("should throw an error if more than one instance has been created", function () { 237 | new NewConstructor(); 238 | new NewConstructor(); 239 | 240 | expect(NewConstructor.getInstance).to.throw(/2 instances/); 241 | }); 242 | 243 | it("should return an instance with a given index", function () { 244 | new NewConstructor(); 245 | const instance2 = new NewConstructor(); 246 | 247 | expect(NewConstructor.getInstance(1)).to.equal(instance2); 248 | }); 249 | 250 | it("should throw an error if not enough instances exist", function () { 251 | new NewConstructor(); 252 | 253 | expect(function () { 254 | NewConstructor.getInstance(1); 255 | }).to.throw(/1 instances/); 256 | }); 257 | }); 258 | 259 | describe("args", function () { 260 | it("should be an empty list if there are no instances", function () { 261 | expect(NewConstructor.args).to.deep.equal([]); 262 | }); 263 | 264 | it("should be a list of constructor arguments", function () { 265 | new NewConstructor("foo", "bar"); 266 | NewConstructor("pi", "biz"); 267 | new NewConstructor("baz", "bla"); 268 | 269 | expect(NewConstructor.args).to.deep.equal([ 270 | ["foo", "bar"], 271 | ["pi", "biz"], 272 | ["baz", "bla"], 273 | ]); 274 | }); 275 | }); 276 | }); 277 | }); 278 | }); 279 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2018 TNG Technology Consulting GmbH 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------