简体   繁体   中英

jest testing with es6 + jspm + systemjs + reactJS

I'm trying to figure out how to make my unit tests in my reactJS ES6 application. My application is already using es6 module system, transpiled with jspm/babel to systemJs.

I found babel-jest as preprocessor but even with it, I can't run my tests because jest can't find SystemJs. ( "System is not defined" error is shown in the console)

In the browser, as explained in jspm documentation, SystemJs is loaded globally. I guess I should load SystemJs inside my preprocessor, but How can I make systemJs available for loading additional modules in my tests?

Thanks in advance

Unfortunately, Jest does not support SystemJS ES6 modules at the moment.

See the following comments:

So it sounds like jest assumes that your modules resolve based on the Node resolution algorithm.

Unfortunately this isn't compatible with SystemJS's resolution algorithm.

If there was a way in jest to set a "custom resolver" algorithm through an API then we could plug jspm into jest, but I'm not sure if this is currently possible.

-- Comment by Guy Bedford , creator of SystemJS, Jun 2015


It is unlikely there'll be official support for [SystemJS] unless it is a community contribution.

-- Comment by @cpojer , Jest Collaborator, Jan 2016


Also see the following issue: Invalid URL is thrown when requiring systemjs in jest test cases

in essence to get Jest to play nice with an app running on JSPM/SystemJS you need to "teach" it about all the mapping it holds in the config.js file (or however you call System.config())

the long answer is that you need to create an entry for each dependency you have installed with JSPM like this:

//jest configuration 
moduleNameMapper: {     
   ...
   "^redux$": "redux@3.6.0",
   ...
}

for each alias you have, you need at least one entry:

moduleNameMapper: {     
        ...
        "^common\\/(.*)": "<rootDir>/src/common/$1", //for a dir alias
       "^actions$": "<rootDir>/src/actions/index", //for a file alias
       ...
}

you also need to have these mappings in your nodeNameMapper :

moduleNameMapper: {     
    ...
         "^npm:(.*)": "<rootDir>/jspm_packages/npm/$1",
            "^github:(.*)": "<rootDir>/jspm_packages/github/$1",
    ...
}

and finally, you need to have this moduleDirectories config:

moduleDirectories: ["node_modules", "jspm_packages/npm", "jspm_packages/github"]

this isnt really practical because you dont want to keep two copies of all your dependencies registry and have to sync them when they change...

so the short and better answer, you use my gulp-jest-jspm plugin :)

even if you dont use gulp, you can use its getJestConfig() method to generate the config for you before you run Jest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM