dimanche 20 décembre 2015

Writing Unit Tests for TSX (TypeScript for JSX/React)

I have been researching a good workflow for developing React based components in TypeScript.

Since 1.6, TypeScript has native support for JSX in TypeScript files through the .tsx extension and with tsd we can get IDE (atom/WebStorm) to support type checking.

However, there does not appear to be a easy way to test React components written in tsx.

Can you share your insights on this?

I am considering (almost obliged to use) Jest as opposed to pure Jasmine because Jest's runtime environment comes with a DOM. However, jest appears to only work with ES2015 through babel and es2015, react presets. Is there a readily available way for Jest to work with tsx?

Currently, I can test React components written in ES2015 like:

//SampleComponent.js
import React from 'react';

class SampleComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (<div className='container'>Hello World!</div>);
  }
}

module.exports = SampleComponent;

and the corresponding test might look like:

// __tests__/SampleComponent-test.js
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';

const SampleComponent = require('../SampleComponent');

describe('SampleComponent', ()=>{
  it("has some text", ()=>{

    const result = TestUtils.renderIntoDocument(
      <SampleComponent />
    );

    const sampleComponentNode = ReactDOM.findDOMNode(result);

    // expect statements

  });
});

this works fine ...

but if we replace the .js extension with .tsx, and change the scriptPreprocessor to be: 'use strict';

var ts = require('typescript');

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;
  },
};

All hell breaks loose, especially with regard to the way TypeScript handle module loading

Aucun commentaire:

Enregistrer un commentaire