how to test a function throws an error using chai and sinon in typescript

First, install @types/chai, @types/mocha, @types/sinon, chai, mocha, sinon, and ts-node packages as dev dependencies.

Then, you can write a test case to check whether a function throws an error in typescript as follows:

index.ts
import { expect } from 'chai';
import sinon from 'sinon';

describe('My function', () => {
  it('should throw an error under certain conditions', () => {
    const myFunc = () => {
      throw new Error('My Error');
    };
    
    const spy = sinon.spy(myFunc);
    
    expect(spy).to.throw(Error);
  });
});
311 chars
15 lines

In the above test case, we are creating a simple function using an arrow function () => {throw new Error('My Error');}. Then we are creating a spy on that function using sinon.spy() method. And finally, we are using expect(spy).to.throw(Error) to check if the function throws an error.

Note that if your function takes any arguments, you need to pass them to sinon.spy() method. For example, sinon.spy(obj, 'method').

Run your tests using mocha and ts-node: mocha --require ts-node/register tests/**/*.test.ts

This will run all test files with .test.ts extension located in tests/ directory.

related categories

gistlibby LogSnag