Created
April 19, 2021 22:41
-
-
Save luke10x/0fefd3337aae552bd765ba4d9fd0f9ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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