Skip to content

Commit

Permalink
Merge pull request #58 from devzeebo/master
Browse files Browse the repository at this point in the history
Fix non-chained default implementations (fixes #57)
  • Loading branch information
timkindberg authored Jan 8, 2021
2 parents 95f53e5 + bf5e3f2 commit bc87ce5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
5 changes: 3 additions & 2 deletions src/when.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class WhenMock {
// Incrementing ids assigned to each call mock to help with sorting as new mocks are added
this.nextCallMockId = 0
this.fn = fn
fn.__whenMock__ = this
this.callMocks = []
this._origMock = fn.getMockImplementation()

Expand Down Expand Up @@ -114,7 +115,7 @@ class WhenMock {

const when = (fn) => {
if (fn.__whenMock__ instanceof WhenMock) return fn.__whenMock__
fn.__whenMock__ = new WhenMock(fn)
const whenMock = new WhenMock(fn)
registry.add(fn)
fn._origMockReset = fn.mockReset
fn.mockReset = () => {
Expand All @@ -123,7 +124,7 @@ const when = (fn) => {
fn._origMockReset = undefined
fn.mockReset()
}
return fn.__whenMock__
return whenMock
}

const resetAllWhenMocks = () => {
Expand Down
27 changes: 26 additions & 1 deletion src/when.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ describe('When', () => {
fn2(1)

// Should be two call lines printed, hence the {2} at the end of the regex
expect(verifyAllWhenMocksCalled).toThrow(/(src\/when\.test\.js:\d{3}(.|\s)*){2}/)
expect(verifyAllWhenMocksCalled).toThrow(/(src(?:\\|\/)when\.test\.js:\d{3}(.|\s)*){2}/)
})
})

Expand Down Expand Up @@ -572,6 +572,31 @@ describe('When', () => {
expect(fn('foo2')).toEqual('newDefault')
})

it('allows defining the default NOT in a chained case', () => {
const fn = jest.fn()

when(fn).mockRejectedValue(false)

when(fn)
.calledWith(expect.anything())
.mockResolvedValue(true)

expect(fn()).rejects.toEqual(false)
})

it('allows overriding the default NOT in a chained case', () => {
const fn = jest.fn()

when(fn).mockReturnValue(1)
when(fn).mockReturnValue(2)

when(fn)
.calledWith(expect.anything())
.mockReturnValue(true)

expect(fn()).toEqual(2)
})

it('will throw because of unintended usage', () => {
const fn = jest.fn()

Expand Down

0 comments on commit bc87ce5

Please sign in to comment.