jest testing with es6 + jspm + systemjs + reactJS

情到浓时终转凉″ 提交于 2020-01-22 03:02:28

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/32945193/jest-testing-with-es6-jspm-systemjs-reactjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!