vuejs / vue-jest

Jest Vue transformer
MIT License
742 stars 159 forks source link

`vue3-jest` - Imports from directories and packages with namespace 'vue' get cut out when running unit tests. #512

Open Giergiel96 opened 1 year ago

Giergiel96 commented 1 year ago

After migrating to vue 3, and vue-jest@29.2.0 some tests stopped working for us. After some digging we found out that if you have a package named like "@some-ui-kit/vue", named imports from it will get cut from the component's scope durin test runtime. Changing the import path to anything different changes the issue, but it used to work perfectly fine with Vue 2 compatible versions.

As you can see, the example "TEST" const disappears from the scope: image image

But if you rename the "package", then it works: image image

Reproduction repo: https://github.com/Giergiel96/repro-vue-jest.git

Giergiel96 commented 1 year ago

After some more digging i found out, that the issue is that the "_vue" variable holding the scope with the imports get overwritten by the template script. This is the code generated by the vue-jest after adding scriptResult, scriptSetupResult and templateResult (generate-code.js): image

lmiller1990 commented 1 year ago

Wait - so the bug is only if your package is named vue?

Not sure how best to fix this one. I guess our code gen isn't ideal.

Giergiel96 commented 1 year ago

This one's weird. It looks like babel creates a namespace out of the last part of the import path (i.e. @random-package/vue or @package/components/vue). When you import anything other from anything that will result in creation of the _vue namespace, then the problem disappears since it will autoincrement and create _vue1, _vue2 starting from the number 1 🤷 What we did for now was to write a babel plugin that runs only during tests, that looks for any _vue variable declaration and does not import from vue directly and "increments" the name to _vue1 so it does not get overwritten by the impots from template code 😂

Giergiel96 commented 1 year ago

Example of that is in the reproduction repo.

lmiller1990 commented 1 year ago

Weird one... I am not sure I have time to fix this, if you want to try, that'd be great. Alternatively - just rename your package to not be named vue. Not ideal, but an easy work around in the mean time.

mrgodhani commented 2 months ago

@Giergiel96 do you have an example of the babel plugin and how you solved it?