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

后端 未结 4 1814
天命终不由人
天命终不由人 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
        })
    

提交回复
热议问题