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.ts311 chars15 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.
gistlibby LogSnag