Skip to content

Instantly share code, notes, and snippets.

@luke10x
Created April 19, 2021 22:41
Show Gist options
  • Save luke10x/0fefd3337aae552bd765ba4d9fd0f9ec to your computer and use it in GitHub Desktop.
Save luke10x/0fefd3337aae552bd765ba4d9fd0f9ec to your computer and use it in GitHub Desktop.
import sinon from 'sinon';
import { stubConstructor } from 'ts-sinon'
export class Calculator {
sum(exp: string): number;
sum(a: number, b: number): number;
sum(...args: any): number {
const summands = args.length === 1
? args[0].split('+').map((x: string) => parseFloat(x))
: args;
return summands.reduce((a: number, b: number) => a + b)
}
}
describe('Calculator', () => {
const calculator = new Calculator();
it('adds numbers', () => {
expect(calculator.sum(2, 3)).toBe(5)
})
it('adds numbers in a string', () => {
expect(calculator.sum('2 + 3')).toBe(5)
})
})
describe('Calculator stub', () => {
const stub = stubConstructor(Calculator);
beforeEach(() => stub.sum.resetHistory())
it('can call the calculator using numbers', () => {
stub.sum(2, 3)
sinon.assert.calledWithMatch(
stub.sum as unknown as sinon.SinonSpy<[a: number, b:number], number>, 2, 3
)
})
it('can call the calculator using a string', () => {
stub.sum('2 + 3')
sinon.assert.calledWithMatch(
stub.sum as unknown as sinon.SinonSpy<[exp: string], number>, '2 + 3'
)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment