在 TypeScript 中检查 sinon 存根的参数

Check arguments of sinon stub in TypeScript

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

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 而不是 expected/actual 值。

您可以使用 Assertions APIsinon。此外,sinon.stub() 方法的 return 值是一个 sinon 存根。因此您可以使用此 return 值而不是使用 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/Whosebug/60034220