我们可以使用sinon.stub而不使用API中的async函数吗

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

我正在使用 mocha chai 运行单元测试用例,并使用 Ssnon.stub 方法来模拟 API 内的数据库函数,并且不在我的 API 中使用异步函数。当我尝试运行测试用例时,它超时并且没有返回响应。

如果我将异步添加到我的 API 并且它工作正常。但我不想在我的 API 中使用异步。

有什么方法可以不使用异步函数来实现这一点吗?

admin.js

app.get("/allcurrency/:id", (req, res) => {
  adminfunctions.getAllCurrency(req, function (data) {
    if (!data.error) {
      res.status(200).send(data);
    } else {
      res.status(500).send(data);
    }
    });
  });

adminfunctions.js

const db = require(globalObject.__lib + 'dbutil');
 getAllCurrency: function (request, response) {
    let sqlText = pgescape(
      `SELECT * FROM EMPLOYEE LIMIT 25`
    );
    db.sqlSelect(sqlText, function (data) {
      return response(data);
    });
  },

dbutil.js

sqlSelect: function (sqltext, qResult) {
    self.dbQuery(sqltext, function (result) {
      globalObject.logger.debug('SQL: ' + sqltext);
      globalObject.logger.debug('RESULT: ' + JSON.stringify(result));
 
      if (result && result.error && result.error === true) {
        return qResult(result);
      } else {
        if (typeof result.length == 'undefined') {
          var tableArray = [];
          result.rows.forEach(function (tRow) {
            tableArray.push(tRow);
          });
        } else {
          var tableArray = [];
          result.forEach(function (vresult) {
            if (vresult.command == 'SELECT') {
              vresult.rows.forEach(function (tRow) {
                tableArray.push(tRow);
              });
            }
          });
        }
        globalObject.logger.debug('TABLE ARRAY: ' + JSON.stringify(tableArray));
        return qResult(tableArray);
      }
    });
  },
  
  
  
  
  
  dbQuery: async function (sqltext, results) {
    let error;
    let client;
    try {
      client = await pool1.connect();
      client.on('error', (err) => clientErrorListener(err));
      const res = await client.query(sqltext);
      await client.query('COMMIT');
      await client.end();
      return results(res);
    } catch (err) {
      let jsonObj = new Object();
      jsonObj.error = true;
      jsonObj.errorMessage = err.message;
      jsonObj.errorStack = err.stack;
      error = jsonObj;
      logger.error('ERROR MESSAGE: --> ' + err.message);
      logger.error(
        'ERROR OCCURED IN LINE & POSITION: --> ' +
          err.line +
          ' : ' +
          err.position
      );
      logger.error('ERROR FULL MESSAGE: ' + err.stack);
      return results(error);
    } finally {
      if (error) {
        logger.error(error);
        // logger.error(sqltext)
      }

      // client.off("error", clientErrorListener);
      client.release(error);*emphasized text*
      client.connection.stream.end();
    }
  },

admin.test.js

it("getallcurrency api = success 200", (done) => {
  const getUserByIdStub = sinon
    .stub(dbutil, "sqlSelect")
    .returns({ id: 1, name: "Test User", email: "[email protected]" });

  chai
    .request(appInstance)
    .get("/allcurrency/1")
    .end((err, res) => {
      expect(res).to.have.status(200);
      done();
      getUserByIdStub.restore();
    });
});

上面的代码没有返回任何响应。

它与下面的代码一起工作,我不想在这里使用异步和等待函数。

app.get("/allcurrency/:id", async (req, res) => {
    const res = await adminfunctions.getAllCurrency(req);
    res.status(200).send(res);*emphasized text*
  });

请帮助我了解如何在此处不使用异步的情况下使用它。

node.js postgresql mocha.js chai sinon
1个回答
1
投票

db.sqlSelect()
方法不是异步函数,它接受回调函数以将数据传递给调用者。使用
sinon.stub().callsFake(fakeFunction)
使存根在调用时调用提供的
fakeFunction
会有所帮助。

例如

dbutil.js

const dbutil = {
    sqlSelect: function (sqltext, qResult) {
        throw new Error('Not implemented');
    },
};

module.exports = dbutil;

adminfunctions.js

const db = require('./dbutil');

const adminfunctions = {
    getAllCurrency: function (request, callback) {
        let sqlText = `SELECT * FROM EMPLOYEE LIMIT 25`;
        db.sqlSelect(sqlText, function (data) {
            callback(data);
        });
    },
};

module.exports = adminfunctions;

app.js

const express = require('express');
const adminfunctions = require('./adminfunctions');

const app = express();

app.get('/allcurrency/:id', (req, res) => {
    adminfunctions.getAllCurrency(req, function (data) {
        if (!data.error) {
            res.status(200).send(data);
        } else {
            res.status(500).send(data);
        }
    });
});

module.exports = app;

admin.test.js

const sinon = require('sinon');
const dbutil = require('./dbutil');
const chai = require('chai');
const chaiHTTP = require('chai-http');
const app = require('./app');

chai.use(chaiHTTP);
const { expect } = chai;

it('getallcurrency api = success 200', (done) => {
    sinon.stub(dbutil, 'sqlSelect').callsFake((sqlText, callback) => {
        callback({ id: 1, name: 'Test User', email: '[email protected]' });
    });

    chai
        .request(app)
        .get('/allcurrency/1')
        .end((err, res) => {
            expect(res).to.have.status(200);
            expect(res.body).to.deep.equal({ id: 1, name: 'Test User', email: '[email protected]' });
            done();
        });
});

测试结果:

  √ getallcurrency api = success 200

  1 passing (16ms)

-------------------|---------|----------|---------|---------|-------------------
File               | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------------|---------|----------|---------|---------|-------------------
All files          |   88.88 |       50 |      80 |   88.88 | 
 adminfunctions.js |     100 |      100 |     100 |     100 | 
 app.js            |   88.88 |       50 |     100 |   88.88 | 11
 dbutil.js         |   66.66 |      100 |       0 |   66.66 | 3
-------------------|---------|----------|---------|---------|-------------------
© www.soinside.com 2019 - 2024. All rights reserved.