vuejs/vue-test-utils-jest-example

how to handle asset imports

phoet opened this issue · 5 comments

phoet commented

when using the jest configuration from a fresh vue-cli setup, or with this template, there is something missing for handling dynamic imports such as images from the asset folder.

i created a minimal reproducible example from this repo, see the diff here:
https://github.com/vuejs/vue-test-utils-jest-example/compare/master...penseo:breaks-when-using-assets?expand=1

i saw that there needs to be some additional configuration for jest to work with webpack on the official documentation: https://facebook.github.io/jest/docs/en/webpack.html

my assumption was that this should be included with the configuration that is generated by default.

please correct my if my assumption is wrong.

this is the error message:

yarn test
yarn test v0.27.5
$ jest
 PASS  test/Message.spec.js
 FAIL  test/MessageToggle.spec.js
  ● Test suite failed to run

    /Users/peterschroder/Documents/javascript/vue-test-utils-jest-example/src/assets/logo1.png:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){�PNG
                                                                                             ^

    SyntaxError: Invalid or unexpected token

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
      at src/components/MessageToggle.vue:12:13
      at Object.<anonymous> (src/components/MessageToggle.vue:49:3)

 PASS  test/List.spec.js

Test Suites: 1 failed, 2 passed, 3 total
Tests:       4 passed, 4 total
Snapshots:   1 passed, 1 total
Time:        2.063s
Ran all test suites.

Thanks for pointing this out.

Here's a workaround:

npm i --save-dev jest-transform-stub
"jest": {
  "transform": {
    ".+\\.(css|styl|less|sass|scss|png|jpg|svg|ttf|woff|woff2)$": "jest-transform-stub"
  }
}

(vuejs-templates/webpack#1317)

phoet commented

@eddyerburgh great, thank you!

Thanks @eddyerburgh!
Might be worth including SVG in that list for the transform also:

".+\\.(css|styl|less|sass|scss|png|jpg|svg|ttf|woff|woff2)$": "jest-transform-stub"

where did you write it?

"jest": {
  "transform": {
    ".+\\.(css|styl|less|sass|scss|png|jpg|svg|ttf|woff|woff2)$": "jest-transform-stub"
  }
}

in jest.config.js?

@moffsugita in package.json