From e8eab36fda5f2cabb19e10c874ef76c75d9d0b04 Mon Sep 17 00:00:00 2001 From: James Garbutt <43081j@users.noreply.github.com> Date: Wed, 20 Nov 2019 22:57:58 +0000 Subject: [PATCH] sinon: strongly type accessors (#40536) --- types/sinon/ts3.1/index.d.ts | 7 ++++++- types/sinon/ts3.1/sinon-tests.ts | 22 +++++++++++++++------- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/types/sinon/ts3.1/index.d.ts b/types/sinon/ts3.1/index.d.ts index 0248f4488b..061b250322 100644 --- a/types/sinon/ts3.1/index.d.ts +++ b/types/sinon/ts3.1/index.d.ts @@ -351,11 +351,16 @@ declare namespace Sinon { * The original method can be restored by calling object.method.restore(). * The returned spy is the function object which replaced the original method. spy === object.method. */ - (obj: T, method: K, types?: string[]): T[K] extends ( + (obj: T, method: K): T[K] extends ( ...args: infer TArgs ) => infer TReturnValue ? SinonSpy : SinonSpy; + + (obj: T, method: K, types: Array<('get'|'set')>): PropertyDescriptor & { + get: SinonSpy<[], T[K]>; + set: SinonSpy<[T[K]], void>; + }; } interface SinonStub diff --git a/types/sinon/ts3.1/sinon-tests.ts b/types/sinon/ts3.1/sinon-tests.ts index fc538ecb08..e1eca9158b 100644 --- a/types/sinon/ts3.1/sinon-tests.ts +++ b/types/sinon/ts3.1/sinon-tests.ts @@ -345,6 +345,10 @@ function testAssert() { function testTypedSpy() { const cls = class { + get accessorTest() { return 5; } + set accessorTest(v: number) { } + get getterTest() { return 5; } + set setterTest(v: number) { } foo(a: number, b: string): number { return 3; } @@ -376,6 +380,16 @@ function testTypedSpy() { stub.withArgs(5, 'x').returns(3); stub.withArgs(sinon.match(5), 'x').returns(5); + + const accessorSpy = sinon.spy(instance, 'accessorTest', ['get', 'set']); + accessorSpy.get.returned(5); + accessorSpy.set.calledWith(55); + + const getterSpy = sinon.spy(instance, 'getterTest', ['get']); + getterSpy.get.returned(5); + + const setterSpy = sinon.spy(instance, 'setterTest', ['set']); + setterSpy.set.calledWith(100); } function testSpy() { @@ -392,19 +406,13 @@ function testSpy() { const spyTwo = sinon.spy().named('spyTwo'); const methodSpy = sinon.spy(instance, 'foo'); // $ExpectType SinonSpy<[], void> - const methodSpy2 = sinon.spy(instance, 'bar', ['set', 'get']); // $ExpectType SinonSpy - const methodSpy3 = sinon.spy(instance, 'foobar'); // $ExpectType SinonSpy<[(string | undefined)?], string | undefined> + const methodSpy2 = sinon.spy(instance, 'foobar'); // $ExpectType SinonSpy<[(string | undefined)?], string | undefined> methodSpy.calledBefore(methodSpy2); methodSpy.calledAfter(methodSpy2); methodSpy.calledImmediatelyBefore(methodSpy2); methodSpy.calledImmediatelyAfter(methodSpy2); - methodSpy.calledBefore(methodSpy3); - methodSpy.calledAfter(methodSpy3); - methodSpy.calledImmediatelyBefore(methodSpy3); - methodSpy.calledImmediatelyAfter(methodSpy3); - let count = 0; count = spy.callCount;