score:4

Accepted answer

this is how i have managed to spy on imported functions using jest.

import everything that is imported in the file you're testing.

mock it in the beforeeach, you can use more complex mocking if you need to return values or whatever.

in the aftereach call jest.clearallmocks() to reset all the functions to normal to stop any mocking falling through to other tests.

putting it all together it looks something like this.

import shallow from 'enzyme'
import * as store from './store' // this should be the actual path from the test file to the import

describe('mocking', () => {
  beforeeach(() => {
    jest.spyon(store, 'handlecancel')
    jest.spyon(store, 'create')
  })

  aftereach(() => {
    jest.clearallmocks();
  })

  test.only('should handle cancel button click', () => {
    const wrapper = shallow(<createform />);
    const cancelbutton = wrapper.find('button').at(1);
    cancelbutton.simulate('click');
    expect(store.handlecancel).tobecalled();
  })
})

also, in case you need to mock a default import you can do so like this. jest.spyon(store, 'default')

score:0

you forgot to tell jest how to mock the store module, in your case it is just undefined.

const store = require('../../src/store');
jest.mock('../../src/store', () =>({
 handlecancel: jest.fn()
}));

test.only('should handle cancel button click', () => {
    const wrapper = shallow(<createform />);
    const cancelbutton = wrapper.find('button').at(1);
    cancelbutton.simulate('click');
    expect(store.default.handlecancel).tobecalled();//i'm not sure about the default here
});

with this solution you tell jest to mock the store with an object that has the handlecancel function which is a jest spy. on this spy you can then test that it was called.


Related Query

More Query from same tag