我有一个检查功能参数的单元测试。
it('Should return product from DB', () => {
stub(ProductModel, 'findById').returns({
lean: stub().returns({ total: 12 }),
});
getProduct(product_id);
expect((ProductModel.findById as any).firstCall.args[0]).to.equal('product_id');
});
我的问题是:还有其他更好的方法吗?我必须始终强制转换为any
以避免出错。我也尝试过stubFunc.calledWith(args)
,但结果是我只得到true / false,而不是期望/实际值。
您可以使用Assertions API中的sinon
。此外,sinon.stub()
方法的返回值是sinon
存根。因此,您可以使用此返回值而不是使用ProductModel.findById
。
例如
index.ts
:
import { ProductModel } from "./model";
function getProduct(id: string) {
return ProductModel.findById(id).lean();
}
export { getProduct };
model.ts
:
class ProductModel {
public static findById(id: string): { lean: () => { total: number } } {
return { lean: () => ({ total: 0 }) };
}
}
export { ProductModel };
index.test.ts
:
import { stub, assert } from "sinon";
import { getProduct } from "./";
import { ProductModel } from "./model";
describe("60034220", () => {
it("should pass", () => {
const product_id = "1";
const leanStub = stub().returns({ total: 12 });
const findByIdStub = stub(ProductModel, "findById").returns({
lean: leanStub,
});
getProduct(product_id);
assert.calledWithExactly(findByIdStub, product_id);
assert.calledOnce(leanStub);
});
});
带有覆盖率报告的单元测试结果:
60034220
✓ should pass
1 passing (28ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 90 | 100 | 66.67 | 94.74 | |
index.test.ts | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
model.ts | 66.67 | 100 | 33.33 | 80 | 3 |
---------------|----------|----------|----------|----------|-------------------|