javascript - 检查 TypeScript 中 sinon stub 的参数

标签 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('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/

相关文章:

javascript - ASP.NET MVC 下拉列表更改以在没有 Javascript 的情况下导致回发

javascript - 每个对象中的事件处理 onclick 正文响应

node.js - Nest 无法解析 PhotoService 的依赖项(?)

css - 从位于 JSON 中的 url 获取图像

javascript - 替换普通 JS 中的innerHTML

javascript - 为什么这些 AngularJS 应用程序不能一起运行?

javascript - puppeteer 选择链接

javascript - 将多个文件浏览到一个包中

node.js - 是否可以将文件系统根目录和/或文档根目录设置为文件系统的某个子目录?

javascript - 如何将成员的所有函数公开为类自己的函数?