How can I mock a fake database for when unit testing against Knex?

后端 未结 4 1799
天命终不由人
天命终不由人 2021-02-13 14:50

I\'ve been using Knex successfully to connect to a backend database. But I want to be able to unit test my code. Is there a way to mock the database connection?

I\'ve tr

相关标签:
4条回答
  • 2021-02-13 15:20

    I'm using jest and you can do something like this:

       jest.mock('knex', () => {
            const fn = () => {
                return {
                    select: jest.fn().mockReturnThis(),
                    from: jest.fn().mockReturnThis(),
                    where: jest.fn().mockReturnThis(),
                    first: jest.fn().mockReturnThis(),
                    insert: jest.fn().mockReturnThis(),
                    raw: jest.fn().mockReturnThis(),
                    then: jest.fn(function (done) {
                      done(null)
                    })
                    
                }
            }
            return fn
        })
    
    0 讨论(0)
  • 2021-02-13 15:31

    I used jest to mock knex but I had to define an object that contains the method that I used. not the most elegant solution but is working

    let knexMock = () => {
        const fn = () => {
            return {
                returning: function() {
                    return {
                        insert: jest.fn().mockImplementation(() => [123123])
                    }
                },
                insert: jest.fn()
            }
        }
        fn.raw = jest.fn()
        return fn
    }
    
    knex.mockImplementation(knexMock)
    
    0 讨论(0)
  • 2021-02-13 15:38

    I have been using in-memory Sqlite3 databases for automated testing with great success. It's not true unit testing however it does run much faster than MySQL or PostgreSQL. I have posted more details about this solution on a different question.

    0 讨论(0)
  • 2021-02-13 15:39

    Using jest:

    Create the file /__mocks__/knex.js in your app root:

    module.exports = () => ({
      select: jest.fn().mockReturnThis(),
      from: jest.fn().mockReturnThis(),
      where: jest.fn().mockReturnThis(),
      first: jest.fn().mockReturnThis(),
      then: jest.fn(function (done) {
        done(null)
      })
    })
    

    Pass the desired return value to done

    0 讨论(0)
提交回复
热议问题