highlightjs / vue-plugin

Highlight.js Vue Plugin
BSD 3-Clause "New" or "Revised" License
200 stars 28 forks source link

How to use hljsVuePlugin in unit test w/ vitest + @testing-library/vue ? #30

Closed smarlhens closed 2 years ago

smarlhens commented 2 years ago

Describe the bug

Hi there 👋🏻 ,

I'm currently using this plugin in my Vue 3 + vite + vitest + @testing-library/vue project and I'm facing an issue when trying to run my test: image

I'm not sure if the error comes from your library, but maybe from my code or from my test implementation. If this is the case I apologize in advance.

Could you help me to solve this problem?

Reproduction

I've created a repo with one test case:

I'm declaring hljsVuePlugin as a global.plugins follwing what I've understood from @vue/test-utils documentation but I do not know how to provide Vue instance 🤔

Repro repository : smarlhens/vue-vite-vitest-highlightjs-vue-plugin

Trinovantes commented 2 years ago

Looks like you're trying to import the IIFE module instead of the ESM module. Try explicitly aliasing @highlightjs/vue-plugin to @highlightjs/vue-plugin/dist/highlightjs-vue.min.js

smarlhens commented 2 years ago

Test is working fine using import hljsVuePlugin from '@highlightjs/vue-plugin/dist/highlightjs-vue.esm.min.js'; but this is more like a workaround than a proper solution.

It's look like vitest (cf. vitest!747: https://github.com/vitest-dev/vitest/issues/747#issuecomment-1038742861 & https://github.com/vitest-dev/vitest/issues/747#issuecomment-1038915678) is using import field to import libraries we use native import. And node doesn't understand module field, so I've tried adding following code to your package.json and it's seems to be working fine:

  "exports": {
    ".": {
      "import": "./dist/highlightjs-vue.esm.min.js",
      "require": "./dist/highlightjs-vue.min.js"
    }
  },

This kind of change can lead to breaking changes (cf. node: package-entry-points) as exports is overriding main declaration in package.json.

I guess you are better suited to defined if this change is possible or not in your codebase. I let you investigate on this subject, I will be glad to help but I'm not sure I have all the knowledge needed.

smarlhens commented 2 years ago

Looks like someone else came up with an MR with a fix https://github.com/highlightjs/vue-plugin/pull/27 👀

smarlhens commented 2 years ago

@joshgoebel are you planning to publish a new release that will contain #27 merged code ?

joshgoebel commented 2 years ago

Sorry for delay. Just tried this now but npm is being stupid... denied my OTP and now it's refusing to publish with npm ERR! Cannot convert undefined or null to object... I'll circle back tomorrow and see if I have better luck.

joshgoebel commented 2 years ago

2.1.1 published.