ds300 / react-native-typescript-transformer

Seamlessly use TypeScript with React Native
MIT License
657 stars 50 forks source link

[Question] How to unit tests react native application using typescript and react-native-typescript-transformer? #51

Closed pumano closed 6 years ago

pumano commented 6 years ago

I get stuck with unit testing react native application. I have fully work application that uses react-native-typescript-transformer in production builds, but when I need to unit test application I use another method.

I use mocha + ts-node + enzyme + react-native-mock, and it's works perfectly for some internal components, but when I mount some component, but that component with 3rd party library components (which contains es6 default imports) I get error:

C:\Repository\myproject\node_modules\react-native-vector-icons\Feather.js:6
import createIconSet from './lib/create-icon-set';
^^^^^^

SyntaxError: Unexpected token import
    at new Script (vm.js:51:7)
    at createScript (vm.js:136:10)
    at Object.runInThisContext (vm.js:197:10)
    at Module._compile (module.js:613:28)
    at Module._extensions..js (module.js:660:10)
    at Object.require.extensions.(anonymous function) [as .js] (C:\Repository\myproject\node_modules\ts-node\src\index.ts:392:14)
    at Module.load (module.js:561:32)
    at tryModuleLoad (module.js:501:12)
    at Function.Module._load (module.js:493:3)
    at Module.require (module.js:593:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\Repository\myproject\src\StatusMainScreen.tsx:23:1)
    at Module._compile (module.js:649:30)
    at Module.m._compile (C:\Repository\myproject\node_modules\ts-node\src\index.ts:400:23)

I think I need babel for that ES6 imports + typescript for my tests and for compiling application code. I really get stuck on this. How do you recommend me to solve that issue? Or can I use react-native-typescript-transformer with ts-node and mocha?

ds300 commented 6 years ago

Hi, sorry for the delay in getting back to you.

This issue is because react-native-vector-icons (like many react-native libraries) do not compile away es6 import syntax before publishing their code to npm. In order to use these files in unit tests, you need to have them compiled with babel. Mocha is probably already capable of doing that, but you need to tell it to also transpile files under node_modules/react-native-vector-icons.

Also, for the record, I highly recommend testing with Jest and ts-jest over mocha and ts-node. It works really nicely :+1:

pumano commented 6 years ago

@ds300 thank you for answer! 👍