Node.js 使用Mocha/Chai测试写函数
我们正在使用Mocha with Chai为我们的Node/MongoDB API编写单元测试。我的问题涉及测试写函数时的建议。具体来说,在不实际更新数据库中的记录的情况下,如何处理测试例如Node.js 使用Mocha/Chai测试写函数,node.js,mongodb,mocha.js,chai,Node.js,Mongodb,Mocha.js,Chai,我们正在使用Mocha with Chai为我们的Node/MongoDB API编写单元测试。我的问题涉及测试写函数时的建议。具体来说,在不实际更新数据库中的记录的情况下,如何处理测试例如update()函数的结果 摩卡咖啡是否有专门的处理方法?是否建议使用测试数据库?或者在做出更改后回滚更改?还是其他选择 下面是我们其中一个测试函数的示例: describe("remove()", function() { let testTeammember, results; bef
update()
函数的结果
摩卡咖啡是否有专门的处理方法?是否建议使用测试数据库?或者在做出更改后回滚更改?还是其他选择
下面是我们其中一个测试函数的示例:
describe("remove()", function() {
let testTeammember, results;
before(async function() {
// Look for a teammember using standard MongoDB syntax
testTeammember = await db.collection("teammembers").findOne();
if (!mongoose.Types.ObjectId.isValid(testTeammember._id)) fail("Failed because id is not a valid Mongo ObjectId");
// Confirm that a teammember is available for testing
if (!testTeammember) throw "Failed to load test teammember";
const teamId = testTeammember._id.toString();
const params = { id: teamId };
const auth = await TestHelper.generateTestAuth("asmith", apikey);
results = await TeamCtlr.remove(params, auth);
});
it("should be truthy if passed valid params and auth", function() {
assert.isOk(results);
});
it("should return a number for the 'count' property", function() {
assert.typeOf(results.count, "number");
});
it("should have a 'count' of 1", function() {
expect(results.count).to.equal(1);
});
it("results should have a property 'data'", function() {
expect(results).to.have.property("data");
});
it("should return an object for the 'data' property", function() {
assert.isObject(results.data);
});
it("should have a property 'deleted' of type 'boolean'", function() {
assert.isBoolean(results.data.deleted);
});
it("should have 'deleted' set to 'true'", function() {
expect(results.data.deleted).to.equal(true);
});
it("should return a JSON object", function() {
expect(results).to.exist;
});
});
因此,对于上面的代码,我想测试
remove()
函数是否按预期工作。但我不想最终将这些更改保存到数据库中的记录。我会使用一个测试数据库,并为它添加虚拟数据,因为它实际上会读/写数据库。我特别做的是在每个测试用例之前将我需要的任何东西插入数据库,然后执行测试。你不想也不能(这不是你的角色)测试数据库功能。因此,您需要模拟数据库功能(而不是使用数据库)。使用mocha模拟的最流行的库是,您可以参考我将使用一个测试数据库,并为它添加虚拟数据,因为它实际上会读/写数据库。我特别做的是在每个测试用例之前将我需要的任何东西插入数据库,然后执行测试。你不想也不能(这不是你的角色)测试数据库功能。因此,您需要模拟数据库功能(而不是使用数据库)。用摩卡来模仿最流行的图书馆是你可以参考的