How to test React components written in TypeScript with Jest?

1,250 views
Skip to first unread message

jfahr...@gmail.com

unread,
Aug 7, 2015, 10:56:56 AM8/7/15
to Jest
Hi,

I'd like to use Jest to test my React components that are written in TypeScript. I'm using TypeScript's nightly build to have JSX support.

This is what my preprocessor.js looks like:

'use strict';

var ts = require('ntypescript');

module.exports = {
process: function(src, path) {
if (path.match(/\.(ts|tsx)$/) && !path.match(/\.d\.ts$/)) {
return ts.transpile(src, {jsx: ts.JsxEmit.React, module: ts.ModuleKind.CommonJS});
}

return src;
},
};


My test is very very simple (and the one assertion is expected to fail):

/// <reference path="../../typings/jest/jest.d.ts"/>
/// <reference path="../../typings/react/react-addons.d.ts"/>

jest.dontMock('../components/MyComponent.tsx');

import React = require('react/addons');
import MyComponent = require('../components/MyComponent.tsx');

describe('MyComponent', () => {
it('checks if it works', () => {
expect(MyComponent).toEqual('bla');
});
});

My "jest" section in my package.json looks like this:

"jest": {
"scriptPreprocessor": "./tools/preprocessor.js",
"unmockedModulePathPatterns": [
"react"
],
"testPathDirs": [
"./app"
],
"testFileExtensions": [
"ts",
"tsx"
]
}

When I run npm test, I get this:

FAIL app/__tests__/MyComponent-test.tsx
SyntaxError: /<snip>/app/__tests__/MyComponent-test.tsx: /<snip>/app/components/MyComponent.tsx: Unexpected token =
1 test failed, 0 tests passed (1 total)
Run time: 0.275s
npm ERR! Test failed. See above for more details.


Is jest simply not compatible with TypeScript? Or am I doing something fundamentally wrong?

Thank you!

Johannes


Ben Alpert

unread,
Aug 7, 2015, 1:55:43 PM8/7/15
to jfahr...@gmail.com, Jest
Should work. Not sure offhand why yours doesn't, but look at the React repo where we have one TypeScript test that works correctly.



--
You received this message because you are subscribed to the Google Groups "Jest" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jestjs+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/jestjs/d646447f-b891-4c68-85b3-82eda77cc149%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

jfahr...@gmail.com

unread,
Aug 7, 2015, 2:03:34 PM8/7/15
to Jest, jfahr...@gmail.com
Hi Ben,

Thank you, I'll check it out. I think my problem is related to this issue: https://github.com/facebook/jest/issues/427
Because that's exactly the behavior I'm experiencing.

- Johannes

jfahr...@gmail.com

unread,
Aug 7, 2015, 2:28:55 PM8/7/15
to Jest, jfahr...@gmail.com
Switching back from node 0.12 to node 0.10.35 solves it.

nkats...@gmail.com

unread,
Dec 19, 2015, 8:56:10 AM12/19/15
to Jest, jfahr...@gmail.com
Is there a work flow for Non react TS apps that use webpack?
Reply all
Reply to author
Forward
0 new messages