Created
October 4, 2024 13:39
-
-
Save alazycoder101/3ad2af0fb21454f187442731a7cff39e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// [email protected] while working on [email protected] | |
describe('setState mock test', () => { | |
let mockCallback; | |
let setState; | |
const receiver = { | |
state: { | |
disabled: false, | |
}, | |
setState(state, callback) { | |
this.state = { ...this.state, ...state } | |
callback && callback() | |
}, | |
} | |
const receiver_working = { | |
state: { | |
disabled: false, | |
}, | |
setState(state, callback) { | |
this.state = { ...this.state, ...state } | |
callback && callback() | |
}, | |
} | |
// spyOn before test cases which is not working but why? | |
// jest.spyOn(receiver, 'setState', { callThrough: true }) | |
jest.spyOn(receiver, 'setState').mockImplementation((state, callback) => { | |
receiver.state = { ...receiver.state, ...state } | |
callback && callback() | |
}) | |
setState = receiver.setState | |
console.log('setState=', setState); | |
beforeEach(() => { | |
// spyOn in beforeEach which is working | |
jest.spyOn(receiver_working, 'setState').mockImplementation((state, callback) => { | |
receiver_working.state = { ...receiver_working.state, ...state } | |
callback && callback() | |
// this will cause looping by calling the mock implementation again | |
//return receiver_working.setState.apply(this, [state, callback]); | |
}) | |
mockCallback = jest.fn(); | |
}); | |
afterEach(() => { | |
jest.restoreAllMocks(); | |
}); | |
test('callback should be called', () => { | |
receiver_working.setState({ disabled: true }, () => { mockCallback(); console.log('setState called'); }); | |
expect(mockCallback).toHaveBeenCalled(); | |
}) | |
test('callback is not called', () => { | |
receiver.setState({ disabled: true }, () => { mockCallback(); console.log('setState called'); }); | |
expect(mockCallback).not.toHaveBeenCalled(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment