gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:22:32 24 4
gpt4 key购买 nike

拜托,我不太知道如何解决这个问题。对这个过程的良好解释将会​​有很大的帮助。感谢期待。

这是我的 Controller

    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
}));
});
});

希望有帮助。

关于javascript - 我正在尝试使用 mocha 和 chai 测试 API 返回 500(内部服务器错误)的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51700828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com