我正在尝试测试我的路线,但我无法存根我的存储库函数,我想存根存储库中调用数据库的函数。 这是我的测试文件
import { expect } from "chai";
import sinon from "sinon";
import request from "supertest";
import app from "../src/app.js";
describe("GET /users", () => {
let fetchStub;
beforeEach(() => {
fetchStub = sinon.stub(
import("../src/repository/product.repository.js"),
"fetch"
);
});
afterEach(() => {
sinon.restore();
});
it("should return One Product", async () => {
const product = {
_id: new ObjectId(),
code: 123456,
url: "https://example.com",
imported_t: "2020-02-07T16:00:00Z",
};
fetchStub.resolves(product);
const res = await request(app)
.get(`/products/findOne/${product.code}`)
.set("x-api-key", "my-api-key");
expect(res.status).to.equal(200);
});
我的存储库
import db from "../db/db.js";
const collection = db.collection("products");
export const fetch = async (code) => {
return await collection.findOne({ code: parseInt(code) });
};
我的控制器
import {
fetch
} from "../repository/product.repository.js";
export const getProduct = async (req, res) => {
try {
const { code } = req.params;
const product = await fetch(code);
if (!product) {
return res.status(404).json({ message: "Product not found" });
}
res.status(200).json(product);
} catch (error) {
console.error(error);
res.status(400).json({ message: error.message });
}
};
当我运行测试时,我收到此错误
TypeError: Cannot stub non-existent property fetch
我被困在这个问题上几个小时了,请帮忙。
问题是我导出存储库函数的方式,我使用:
export default {
fetch,
};
相反
export const fetch = () => {}
在测试文件中,我用这种方式来存根我的存储库函数
import repository from "../src/repository/product.repository.js";
fetchStub = sinon.stub(repository, "fetch");
现在Sinon可以识别我的fetch函数了,当然我也必须重构我的控制器