简体   繁体   中英

jest check module function calls count

I am pretty new to javascript and jest too and I have this use case in my tests

    jest.mock('./db' , ()=>{
    saveProduct: (product)=>{
    //someLogic
    return
    },
    updateProduct: (product)=>{
    //someLogic
    return
    }
})

This works fine and I can run my tests against it, but I still want to assert in my test cases that updateProduct is called 3 times, how can I achieve this?

Here is an example how can you test these mock fn

const saveProductMock = jest.fn((product)=>{
    //someLogic
    return
});

const updateProductMock = jest.fn((product)=>{
    //someLogic
    return
})

 jest.mock('./db' , ()=>{
    saveProduct: saveProductMock,
    updateProduct: updateProductMock
})
expect(saveProductMock).toHaveBeenCalled()
expect(saveProductMock.mock.calls[0][0]).toBe(product)

You run mock on an exported module, then everywhere you import the module, it becomes mocked.

import db from './db'; // import db

jest.mock('./db', () => ({ // I think you want to return an object
  saveProduct: (product) => {
    //someLogic
    return
  },
  updateProduct: (product) => {
    //someLogic
    return
  }
}));


// assert
expect(db.updatePorduct).toHaveBeenCalledTimes(3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM