Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test: Reactive spies preserve the this instance #28445

Merged
merged 1 commit into from
Jul 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading