我有一个单元测试来检查函数的参数。
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.usedWith(args)
,但结果我只得到 true/false 而不是预期/实际值。
最佳答案
您可以使用Assertions API sinon
。此外,sinon.stub()
方法的返回值是一个sinon
stub 。因此,您可以使用此返回值,而不是使用 ProductModel.findById
。通过这样做,您不需要显式地类型转换为 any
。
例如
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 |
---------------|----------|----------|----------|----------|-------------------|
源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/60034220
关于javascript - 检查 TypeScript 中 sinon stub 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60034220/