我正在尝试使用mocha和chai测试API返回500(内部服务器错误)的条件

时间:2018-08-06 05:03:40

标签: javascript mocha chai

请,我对如何解决这个问题并不了解。对过程进行良好的解释将有很大帮助。谢谢您。

这是我的控制人

    async getAllEntries(req, res) {
    try {
      const userId = req.userData.userID;

      const query = await client.query(
        `SELECT * FROM entries WHERE user_id=($1) ORDER BY entry_id ASC;`, [
          userId,
        ],
      );
      const entries = query.rows;
      const count = entries.length;

      if (count === 0) {
        return res.status(200).json({
          message: 'There\'s no entry to display',
        });
      }

      return res.status(200).json({
        message: "List of all entries",
        "Number of entries added": count,
        entries,
      });
    } catch (error) {
      return res.status(500).json({
        message: "Error processing request",
        error,
      });
    }
  }

1 个答案:

答案 0 :(得分:1)

在这种情况下,我要做的是使client.query进程失败。因此,根据您的代码,它将转到catch语句。

const chai = require('chai');
const assert = chai.assert;
const sinon = require('sinon');

const client = require('...'); // path to your client library
const controller = require('...'); // path to your controller file

describe('controller test', function() {
  let req;
  let res;

  // error object to be used in rejection of `client.query`
  const error = new Error('something weird');

  beforeEach(function() {
    req = sinon.spy();

    // we need to use `stub` for status because it has chain method subsequently
    // and for `json` we just need to spy it
    res = {
      status: sinon.stub().returnsThis(),
      json: sinon.spy()
    };

    // here we reject the query with specified error
    sinon.stub(client, 'query').rejects(error);
  });

  afterEach(function() {
    sinon.restore();
  })

  it('catches error', async function() {    
    await controller.getAllEntries(req, res);

    // checking if `res` is called properly
    assert(res.status.calledWith(500));
    assert(res.json.calledWith({
      message: 'Error processing request',
      error
    }));
  });
});

希望有帮助。