5

I'm trying to test a component that imports a .gql file. When I try to build the component in a Jest file, I receive this error:

( object. anonymous function(module exports require __dirname __filename global jest) {
query getUser {                                                
      ˆˆˆˆˆˆˆ
<script>
import GET_USER from 'PATH';
ˆ

Does anyone have any idea of how to ignore the import? Because I don't need to test the GraphQL call.

jvpcavalcante
  • 53
  • 1
  • 6
  • Can you please edit your question and replace the image with the actual error message? This will help other users find your question when they encounter the same error. – Daniel Rearden Jun 12 '19 at 18:42

1 Answers1

13

GraphQL documents (which typically have a .gql extension) can be imported directly if you use webpack and utilize the loader that comes with graphql-tag. Jest does not work with webpack out of the box and needs to be configured to handle any imports of asset files like stylesheets, images, etc. This process is outlined in the docs.

According to the graphql-tag documentation:

Testing environments that don't support Webpack require additional configuration. For Jest use jest-transform-graphql.

So you can utilize jest-transform-graphql along with the babel-jest plugin, which you're probably already using:

"jest": {
  "transform": {
    "\\.(gql|graphql)$": "jest-transform-graphql",
    ".*": "babel-jest"
  }
}

Mocking the file is technically possible by adding the moduleNameMapper config option as shown in the docs, however, doing so is likely to break your components.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • 4
    I had this issue on my `nuxt` project, the error disappeared after adding `jest-transform-graphql` as above and also adding `moduleFileExtensions: ['js', 'vue', 'json', 'gql'],`. – bob Aug 30 '19 at 03:05
  • `jest-transform-graphql` doesn't work with newer jest versions (>= v28). There is an issue tracking it and a workaround is explained [here](https://github.com/remind101/jest-transform-graphql/issues/13#issuecomment-1367564978). – MkMan Apr 19 '23 at 23:52