Skip to content

Commit

Permalink
fix: Correctly throw error values from method expectations
Browse files Browse the repository at this point in the history
The following should now throw an error, just like property and function
expectations:

```ts
when(foo.bar()).thenThrow();

instance(foo).bar(); // throws
```
  • Loading branch information
NiGhTTraX committed Jun 24, 2021
1 parent a4084a8 commit a1ad324
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/expectation/repository/base-repository.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { returnOrThrow } from '../../instance/instance';
import { ApplyProp, Expectation } from '../expectation';
import { CallMap, ExpectationRepository } from './expectation-repository';
import { Property } from '../../proxy';
Expand Down Expand Up @@ -61,7 +62,7 @@ export abstract class BaseRepository implements ExpectationRepository {
this.recordExpected(property, args);
this.countAndConsume(callExpectation);

return callExpectation.expectation.returnValue.value;
return returnOrThrow(callExpectation.expectation.returnValue.value);
}

this.recordUnexpected(property, args);
Expand Down
11 changes: 11 additions & 0 deletions src/expectation/repository/repo.contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,17 @@ export const repoContractTests: ExpectationRepositoryContract = {
expect(repo.get('foo')()).toEqual(23);
},
},
{
name: 'should throw if the value is an error',
test: (repo) => () => {
const expectation = new MatchingCallExpectation('foo', {
value: new Error(),
});
repo.add(expectation);

expect(() => repo.get('foo')()).toThrow();
},
},
],

'unmet expectations': [
Expand Down
2 changes: 1 addition & 1 deletion src/instance/instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { createProxy } from '../proxy';
* Return the expectation's return value. If the value is an error then
* throw it.
*/
const returnOrThrow = (returnValue: any) => {
export const returnOrThrow = (returnValue: any) => {
if (returnValue instanceof Error) {
throw returnValue;
}
Expand Down
11 changes: 11 additions & 0 deletions tests/e2e.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,17 @@ describe('e2e', () => {
expect(instance(foo).bar(1)).toEqual(23);
});

it('should set expectation on method to throw', () => {
interface Foo {
bar(x: number): number;
}

const foo = mock<Foo>();
when(foo.bar(1)).thenThrow();

expect(() => instance(foo).bar(1)).toThrow();
});

it('should set expectation on member', () => {
interface Foo {
bar: number;
Expand Down

0 comments on commit a1ad324

Please sign in to comment.