Skip to content

Commit

Permalink
Merge pull request #28445 from storybookjs/kasper/reactive-this
Browse files Browse the repository at this point in the history
Test: Reactive spies preserve the this instance
(cherry picked from commit 74e3aa9)
  • Loading branch information
valentinpalkovic authored and storybook-bot committed Jul 8, 2024
1 parent c51ec9d commit d16d950
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
26 changes: 25 additions & 1 deletion code/lib/test/src/spy.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { it, vi, expect, beforeEach } from 'vitest';
import { fn, onMockCall } from './spy';
import { fn, onMockCall, spyOn } from './spy';

const vitestSpy = vi.fn();

Expand All @@ -13,3 +13,27 @@ it('mocks are reactive', () => {
storybookSpy(1);
expect(vitestSpy).toHaveBeenCalledWith(storybookSpy, [1]);
});

class Foo {
bar = 'bar';

transform(postfix: string) {
return this.bar + postfix;
}
}
const foo = new Foo();

it('this is correctly binded when making spies reactive', () => {
const storybookSpy = spyOn(foo, 'transform');
expect(foo.transform('!')).toEqual('bar!');
expect(vitestSpy).toHaveBeenCalledWith(storybookSpy, ['!']);
});

it('this is correctly binded after mock implementation', () => {
const storybookSpy = spyOn(foo, 'transform').mockImplementation(function (this: Foo) {
return this.bar + 'mocked';
});

expect(foo.transform('!')).toEqual('barmocked');
expect(vitestSpy).toHaveBeenCalledWith(storybookSpy, ['!']);
});
6 changes: 3 additions & 3 deletions code/lib/test/src/spy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ function reactiveMock(mock: MockInstance) {

function listenWhenCalled(mock: MockInstance) {
const state = tinyspy.getInternalState(mock as unknown as SpyInternalImpl);
const impl = state.impl?.bind(null);
state.willCall((...args) => {
const impl = state.impl;
state.willCall(function (this: unknown, ...args) {
listeners.forEach((listener) => listener(mock, args));
return impl?.(...args);
return impl?.apply(this, args);
});
return mock;
}
Expand Down

0 comments on commit d16d950

Please sign in to comment.