Skip to content

Commit

Permalink
Fix type definitions for promises
Browse files Browse the repository at this point in the history
When calling `mockResolvedValue` (-`Once`), the argument should be
the expected return value unwrapped from its Promise. Likewise,
when mocking a rejected value, the passed argument needs not
necessarily be of the same type as the expected successful return
value.
  • Loading branch information
Vinnl committed Oct 6, 2020
1 parent 999ee46 commit 269912f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -4,6 +4,8 @@

### Fixes

- `[jest-mock]` Fix typings for `mockResolvedValue`, `mockResolvedValueOnce`, `mockRejectedValue` and `mockRejectedValueOnce`

### Chore & Maintenance

### Performance
Expand Down
22 changes: 12 additions & 10 deletions packages/jest-mock/src/index.ts
Expand Up @@ -63,13 +63,15 @@ namespace JestMock {
mockReturnThis(): this;
mockReturnValue(value: T): this;
mockReturnValueOnce(value: T): this;
mockResolvedValue(value: T): this;
mockResolvedValueOnce(value: T): this;
mockRejectedValue(value: T): this;
mockRejectedValueOnce(value: T): this;
mockResolvedValue(value: Unpromisify<T>): this;
mockResolvedValueOnce(value: Unpromisify<T>): this;
mockRejectedValue(value: unknown): this;
mockRejectedValueOnce(value: unknown): this;
}
}

type Unpromisify<T> = T extends Promise<infer R> ? R : never;

/**
* Possible types of a MockFunctionResult.
* 'return': The call completed by returning normally.
Expand Down Expand Up @@ -661,20 +663,20 @@ class ModuleMockerClass {
// next function call will return this value or default return value
f.mockImplementationOnce(() => value);

f.mockResolvedValueOnce = (value: T) =>
f.mockImplementationOnce(() => Promise.resolve(value));
f.mockResolvedValueOnce = (value: Unpromisify<T>) =>
f.mockImplementationOnce(() => Promise.resolve(value as T));

f.mockRejectedValueOnce = (value: T) =>
f.mockRejectedValueOnce = (value: unknown) =>
f.mockImplementationOnce(() => Promise.reject(value));

f.mockReturnValue = (value: T) =>
// next function call will return specified return value or this one
f.mockImplementation(() => value);

f.mockResolvedValue = (value: T) =>
f.mockImplementation(() => Promise.resolve(value));
f.mockResolvedValue = (value: Unpromisify<T>) =>
f.mockImplementation(() => Promise.resolve(value as T));

f.mockRejectedValue = (value: T) =>
f.mockRejectedValue = (value: unknown) =>
f.mockImplementation(() => Promise.reject(value));

f.mockImplementationOnce = (
Expand Down

0 comments on commit 269912f

Please sign in to comment.