How to mock specific function in object using Jest?

后端 未结 2 1735
情歌与酒
情歌与酒 2020-12-31 18:41

I\'m testing a React/Reflux application using Jest. I have the following function in a store:

onLoad: function() {
  c         


        
相关标签:
2条回答
  • 2020-12-31 19:16

    I have found jest mock instance function It's here

    eg:

    import expect from 'expect';
    
    jest.mock('../libs/utils/Master');
    import Master from '../libs/utils/Master';
    
    Master.mockImplementation(() => {
      return {
        returnOne: jest.fn().mockReturnValueOnce(1)
      }
    })
    describe('test Master', function() {
      it('test search', function() {
        let master = new Master();
        expect(master.returnOne()).toEqual(1);
      });
    });
    
    0 讨论(0)
  • 2020-12-31 19:31

    Almost there, all you need to do is

    const onLoad = jest.fn().mockImplementation(function () {
        var p1 = new Post();//Add your stuff here
        this.posts = [p1];
        console.log("mocked function");
      });
    PostStore.onLoad = onLoad.bind(PostStore); //PostStore is your object.
    
    0 讨论(0)
提交回复
热议问题