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