TypeScript default import error

I am trying to set up a project and run tests with mocha with the mjackson/expect library for approval. My code for testing:

 // inside src/lib/math.ts export function sum(a: number, b: number): number { return a + b; } 

and my test is as follows:

 // inside src/tests/math.tests.ts /// <reference path="../../typings/main/ambient/mocha/mocha.d.ts" /> /// <reference path="../../typings/main/ambient/expect/expect.d.ts" /> import expect from 'expect'; import {sum} from '../lib/math'; describe('sum', () => { it('should add two numbers', () => { expect(sum(1, 2)).toEqual(3); }); }); 

I can compile the code using tsc using the following command:

find src -name *.ts | xargs tsc --declaration --sourceMap --module commonjs --target es5 --listFiles --outDir .

However, when I run mocha from the project directory using the following command:

mocha tests

In my tests, I see the following error:

TypeError: expect_1.default is not a function

When I open the compiled version of my math.tests.ts , I see the following line at the top of the translated code:

var expect_1 = require('expect');

It is beautiful and as expected. However, when I look at the test where expect is called, I see the following line:

 expect_1.default(math_1.sum(1, 2)).toEqual(3); 

Now this line of code seems wrong. The expect library is supplied as an ES6 module, and the expect function is the default export from the module.

However, the TypeScript compiler released the code in my test, where it tries to access the default attribute on expect_1 , which is an import from the expect library. The expect_1 link expect_1 is the default exported function, which I need in my tests, not expect_1.default , which is invalid.

It should be noted that if I changed my math.tests.ts to import expect using the older require syntax. Everything is working fine.

Please help me understand what I am missing.

PS I am using TypeScript 1.8.2 with Node v4.3.1.

+7
javascript module typescript
source share
2 answers

It looks like the waitspace type in the npm package is incorrect ( @ types / expect ). You can make a small workaround to save type checking:

 import * as _expect from 'expect'; const expect = _expect as any as typeof _expect.default; 
+3
source share

It seems that your expected version of the package does not match its declaration. I just installed it and found that it has a default entry:

 exports['default'] = expect; module.exports = exports['default']; 
0
source share

All Articles