簡體   English   中英

我正在嘗試使用mocha和chai測試API返回500(內部服務器錯誤)的條件

[英]I am trying to test a condition wherein the API returns 500 (internal server error) using mocha and 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,
      });
    }
  }

對於這種情況,我要做的是使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
    }));
  });
});

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM