UNPKG

1.52 kBPlain TextView Raw
1// Copyright IBM Corp. and LoopBack contributors 2018,2020. All Rights Reserved.
2// Node module: @loopback/testlab
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6import sinon, {SinonSpy} from 'sinon';
7
8export {sinon, SinonSpy};
9
10export type StubbedInstanceWithSinonAccessor<T> = T & {
11 stubs: sinon.SinonStubbedInstance<T>;
12};
13
14/**
15 * Creates a new object with the given functions as the prototype and stubs all
16 * implemented functions.
17 *
18 * Note: The given constructor function is not invoked. See also the stub API.
19 *
20 * This is a helper method replacing `sinon.createStubInstance` and working
21 * around the limitations of TypeScript and Sinon, where Sinon is not able to
22 * list private/protected members in the type definition of the stub instance
23 * and therefore the stub instance cannot be assigned to places expecting TType.
24 * See also
25 * - https://github.com/Microsoft/TypeScript/issues/13543
26 * - https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14811
27 *
28 * @typeParam TType - Type being stubbed.
29 * @param constructor - Object or class to stub.
30 * @returns A stubbed version of the constructor, with an extra property `stubs`
31 * providing access to stub API for individual methods.
32 */
33export function createStubInstance<TType>(
34 constructor: sinon.StubbableType<TType>,
35): StubbedInstanceWithSinonAccessor<TType> {
36 const stub = sinon.createStubInstance(constructor);
37 return Object.assign(stub as TType, {stubs: stub});
38}