Reputation: 353
I have a unit test that checks arguments of the function.
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');
});
My question is: Is there any other better way to do it? I have to always cast to any
to avoid getting error.
I have also tried stubFunc.calledWith(args)
, but in a result I get only true/false instead of expected/actual values.
Upvotes: 1
Views: 1856
Reputation: 102207
You can use Assertions API of sinon
. Besides, the return value of sinon.stub()
method is a sinon
stub. So you can use this return value instead of using ProductModel.findById
. By doing this, you don't need to type cast to any
explicitly.
E.g.
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);
});
});
Unit test results with coverage report:
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 |
---------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/60034220
Upvotes: 2