Skip to content

Instantly share code, notes, and snippets.

@alazycoder101
Created October 4, 2024 13:39
Show Gist options
  • Save alazycoder101/3ad2af0fb21454f187442731a7cff39e to your computer and use it in GitHub Desktop.
Save alazycoder101/3ad2af0fb21454f187442731a7cff39e to your computer and use it in GitHub Desktop.
// [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