Skip to content

Commit

Permalink
Add .clear method to mocks. Fix .reset (#291)
Browse files Browse the repository at this point in the history
* fix(mocks): reset should empty calls

Fixes #290

* Add .clear method to mocks

* Add changeset

---------

Co-authored-by: Piotr Szlachciak <[email protected]>
  • Loading branch information
dhardtke and sz-piotr authored Apr 21, 2024
1 parent e5ce81a commit 46f000c
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/five-cycles-type.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"earl": minor
---

Add .clear to mocks which clears the calls array. Fixes .reset not clearing the calls.
22 changes: 22 additions & 0 deletions packages/earl/src/mocks/mockFn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,28 @@ describe('Mock', () => {
fn.reset()
expect(fn('foo', 'bar')).to.equal(6)
})

it('clears mock calls', () => {
const fn = mockFn((_a: string, _b: string) => {})
fn('foo', 'bar')
expect(fn.calls).to.deep.equal([
{ args: ['foo', 'bar'], result: { type: 'return', value: undefined } },
])
fn.reset()
expect(fn.calls).to.be.empty
})
})

describe('.clear', () => {
it('clears mock calls', () => {
const fn = mockFn((_a: string, _b: string) => {})
fn('foo', 'bar')
expect(fn.calls).to.deep.equal([
{ args: ['foo', 'bar'], result: { type: 'return', value: undefined } },
])
fn.clear()
expect(fn.calls).to.be.empty
})
})

describe('.given', () => {
Expand Down
5 changes: 5 additions & 0 deletions packages/earl/src/mocks/mockFn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,16 @@ export function mockFn<A extends any[], R>(
defaultSpec = { type: 'not-ready' }
oneTimeOverrides = []
parameterOverrides = []
mock.clear()
if (defaultImplementation) {
mock.executes(defaultImplementation)
}
}

mock.clear = function () {
mock.calls = []
}

mock.returns = function (value: any) {
defaultSpec = { type: 'return', value }
return mock
Expand Down
6 changes: 6 additions & 0 deletions packages/earl/src/mocks/types/MockFunction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,12 @@ export interface MockFunction<A extends any[], R> {
*/
reset(): void

/**
* Clears any memory of calls to this mock. After clearing the mock will act
* as if it was never called.
*/
clear(): void

/**
* Specifies a different behavior when other arguments are given.
*
Expand Down

0 comments on commit 46f000c

Please sign in to comment.