Javascript 检查TypeScript中sinon存根的参数

Javascript 检查TypeScript中sinon存根的参数,javascript,node.js,typescript,unit-testing,sinon,Javascript,Node.js,Typescript,Unit Testing,Sinon,我有一个检查函数参数的单元测试 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(

我有一个检查函数参数的单元测试

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,而不是预期值/实际值。

您可以使用
sinon
。此外,
sinon.stub()
方法的返回值是一个
sinon
stub。因此,您可以使用此返回值,而不是使用
ProductModel.findById
。通过这样做,您不需要显式地键入cast to
any

例如

index.ts

从“/model”导入{ProductModel};
函数getProduct(id:string){
return ProductModel.findById(id).lean();
}
导出{getProduct};
model.ts

类产品模型{
公共静态findById(id:string):{lean:()=>{total:number}{
返回{lean:()=>({total:0})};
}
}
导出{ProductModel};
index.test.ts

从“sinon”导入{stub,assert};
从“/”导入{getProduct};
从“/model”导入{ProductModel};
描述(“60034220”,()=>{
它(“应该通过”,()=>{
const product_id=“1”;
const leanStub=stub()。返回({total:12});
const findByIdStub=stub(ProductModel,“findById”)。返回({
lean:leanStub,
});
getProduct(产品标识);
assert.calledWithJustice(findByidSub,产品id);
assert.calledOnce(leanStub);
});
});
单元测试结果和覆盖率报告:

60034220
✓ 应该通过
1次通过(28毫秒)
---------------|----------|----------|----------|----------|-------------------|
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s|
---------------|----------|----------|----------|----------|-------------------|
所有文件| 90 | 100 | 66.67 | 94.74 ||
index.test.ts | 100 | 100 | 100 | 100 ||
index.ts | 100 | 100 | 100 | 100 ||
型号.ts | 66.67 | 100 | 33.33 | 80 | 3|
---------------|----------|----------|----------|----------|-------------------|
源代码: