Does anyone know the correct way to set up testing with ts-node in typescript to have Mocha and Chai and Sinon all recognized globally without the need to manually import in every test file? I have all types definitions included in the project, including mocha, sinon, chai. I have the following (which works and runs tests correctly):
mocha.opts:
--require ts-node/register
--option value spec/**/*.spec.ts
--require spec/bootstrap/test-setup.js
--recursive
--retries 0
--sort
--timeout 10000
--ui bdd
Test script in package.json:
"test": "yarn build && NODE_ENV=test nyc mocha ./spec/bootstrap/test-helper.js --opts ./spec/mocha.opts"
I have 2 helper methods (which for some reason I have to do in JS)
test-setup.js:
require('mocha');
var chai = require('chai');
chai.use(require('chai-as-promised'));
chai.use(require('sinon-chai'));
global.expect = chai.expect;
global.Promise = require('bluebird');
test-helper.js:
const sinon = require('sinon');
const _ = require('lodash');
const db = require('../../src/models');
before(() => {
global.sandbox = sinon.sandbox.create();
});
afterEach(function () {
global.sandbox.restore();
});
after(() => {
db.default.sequelize.close();
});
Finally a junk spec for testing setup:
describe('app', () => {
const bar = {
foo: () => 1,
};
it('asserts 1 === 1', () => {
const stub = sandbox.stub(bar, 'foo').returns(3);
const result = bar.foo();
expect(result).to.eq(3);
expect(stub).to.have.callCount(1);
expect(1).to.eq(1);
});
it('tests stubs reset', () => {
expect(bar.foo()).to.eq(1);
});
});
A couple notes here:
- This works, it transpiles and runs the tests correctly. If i remove the seemingly pointless
require('mocha')
it shows error highlighting forit
anddescribe
as well, but again still runs. - The only "issue" is the error highlighting and lack of auto complete for sinon and chai stuff in vs code. This is very close to my test setup in node js, which works 100% fine.
But again I stress, this works, it just feels dubiously hacky and I would like to figure out if I can A) do this all in TS, rather than having JS setup files, and B) fix incorrect ts error highlighting in this scenario.