如何模拟路由中使用的knex函数

问题描述 投票:1回答:1

我具有通过环境配置knex的功能

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

我在route.js中使用此功能

module.exports = (app) => {
    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))
        })

 }

我的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')
            .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();
            })

当我执行测试文件时,knexConnection.raw被存根,并显示当前时间。测试失败。它说该存根从未被调用过。

我已经尝试了好几天,但仍然无法正常工作。任何想法如何存根knex查询?

UPDATE

经过数小时的努力后,我发现存根被跳过了,因为应用程序在存根之前实例化了。因此存根永远不会被加载。

我的服务器结构具有此结构。

-server.js

//...all server stuff
//load all modeles routes using route
route(app)

这是我的index.js,因为我在服务器应用中动态加载了所有路由。

var fs = require("fs");

module.exports = app => {
  fs.readdirSync(__dirname).forEach(file => {
    if (file == "index.js") return;

    const name = file.substr(0, file.indexOf("."));
    require("./" + name)(app);
  });
};

我的模拟游戏仍被跳过,并且会先调用应用程序。

node.js unit-testing sinon knex.js proxyquire
1个回答
1
投票

您不能更改原始值,因为knexConnection是函数而不是对象。

© www.soinside.com 2019 - 2024. All rights reserved.