Skip to content
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
11 changes: 11 additions & 0 deletions e2e/spy/spyOn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,15 @@ describe('test spyOn', () => {
spy.mockReset();
expect(util1.sayHi()).toBe('hi');
});

it('spyOn re-spy', () => {
const hi = {
sayHi: () => 'hi',
};
rstest.spyOn(hi, 'sayHi').mockImplementation(() => 'hello');

expect(hi.sayHi()).toBe('hello');
// should get the same spy instance
expect(rstest.spyOn(hi, 'sayHi')).toBeCalled();
});
});
16 changes: 16 additions & 0 deletions packages/core/src/runtime/api/spy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,22 @@ export const initSpy = (): Pick<
methodName: K,
accessType?: 'get' | 'set',
): MockInstance<T[K]> => {
if (accessType) {
const descriptor = Object.getOwnPropertyDescriptor(obj, methodName);
const accessor =
accessType === 'get'
? Reflect.get(descriptor ?? {}, 'get')
: Reflect.get(descriptor ?? {}, 'set');
if (typeof accessor === 'function' && isMockFunction(accessor)) {
return accessor as MockInstance<T[K]>;
}
} else {
const method = obj[methodName];
if (isMockFunction(method)) {
return method;
}
}

const accessTypeMap = {
get: 'getter',
set: 'setter',
Expand Down
13 changes: 13 additions & 0 deletions website/docs/en/api/runtime-api/rstest/mock-functions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,19 @@ expect(hi.sayHi()).toBe('hi');
expect(spy).toHaveBeenCalled();
```

If you call `rstest.spyOn` multiple times for the same method, Rstest reuses the existing spy instead of redefining it.

```ts
const hi = {
sayHi: () => 'hi',
};
rstest.spyOn(hi, 'sayHi').mockImplementation(() => 'hello');

expect(hi.sayHi()).toBe('hello');
// should get the same spy instance
expect(rstest.spyOn(hi, 'sayHi')).toBeCalled();
```

## rstest.isMockFunction

- **Alias:** `rs.isMockFunction`
Expand Down
14 changes: 14 additions & 0 deletions website/docs/zh/api/runtime-api/rstest/mock-functions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,20 @@ expect(hi.sayHi()).toBe('hi');
expect(spy).toHaveBeenCalled();
```

对同一个方法重复调用 `rstest.spyOn` 时,会返回已有的 spy,而不是重新定义。

```ts
const hi = {
sayHi: () => 'hi',
};
rstest.spyOn(hi, 'sayHi').mockImplementation(() => 'hello');

expect(hi.sayHi()).toBe('hello');

// 返回的 spy 实例与第一次调用相同
expect(rstest.spyOn(hi, 'sayHi')).toBeCalled();
```

## rstest.isMockFunction

- **别名:** `rs.isMockFunction`
Expand Down
Loading