Saturday, 28 September 2019

How to mock knex query

I have this function that configure knex by environment

const knexConnection = () => {
   const config = require('./connection')[environment];
   return knex(config) 
}

I use this function in my route.js

app.get("/test", (req,res)=>{
        knexConnection().raw("SELECT NOW() as time").then(result => {
            const time = _.get(result.rows[0],'time')
            res.send(time);
        }).catch(err => throw(err))
    })

my test file for the route.js

const sinon = require("sinon");
const chai = require("chai");
const mock = require('proxyquire')
const httpStatus = require('http-status');
const expect = chai.expect;

    const myStub = sandbox.stub().resolves("Query executed")
     const route = mock('../routes', {'../../knexConntection':knexConnection : { raw: myStub }}})

        route(app)

        chai.request(app)
            .get('/test/pg')
            .set('content-type', 'application/x-www-form-urlencoded')
            .end((err, res) => {
                if (err) done(err);
                expect(myStub).to.have.been.called;
                expect(res.status).to.equal(200)
                done();
            })

When i execute the test file, the knexConnection.raw is stubbed and it shows the current time. and the test fails. it says the stub was never called.

I've been trying for days and it still hasnt work. any idea how to stub knex query?



from How to mock knex query

No comments:

Post a Comment