【发布时间】:2020-12-12 03:26:11
【问题描述】:
我在 node.js 中有这个 fn,它从文件中读取 json 数据。
async getAllProducts() {
try {
return JSON.parse(await fs.promises.readFile("data/products.json"));
} catch (error) {
if (error.message === "Unexpected end of JSON input") {
throw new NoProductsExistError("The File is Empty");
}
throw new FileReadingError("Error Reading File");
}
}
我正在尝试存根该方法。到目前为止,这是我的代码。
const chai = require("chai");
const expect = chai.expect;
const sinon = require("sinon");
const dao = require("./dao");
const fs = require("fs");
describe("getAllProducts", () => {
it("should return all products", () => {
sinon
.stub(fs.promises, "readFile")
.withArgs("data/products.json")
.returns(
JSON.stringify([
{
productId: 101,
productName: "Sony XB450AP Wired Headset"
},
{
productId: 102,
productName: "Sony XB950"
}
])
);
expect(dao.getAllProducts()).to.equal([
{
productId: 101,
productName: "Sony XB450AP Wired Headset"
},
{
productId: 102,
productName: "Sony XB950"
}
]);
});
});
但是,当我在配置 mocha 的情况下运行 npm test 时,我得到了这个
1) getAllProducts
should return all products:
AssertionError: expected {} to equal [ Array(2) ]
at Context.<anonymous> (data\dao.spec.js:27:35)
at processImmediate (internal/timers.js:458:21)
不知道如何解决这个问题。非常感谢任何帮助
【问题讨论】:
标签: javascript unit-testing chai sinon fs