2

I'm currently working on an existing React app and have to add Vitest to it.

The problem I'm facing is that globals are injected using the inject function from @rollup/plugin-inject in my vite.config.js.

  plugins: [
    viteReact(),
    inject({
      _: 'lodash',
      __: [path.join(path.resolve(), 'src/app/core'), 'evemit'],
      moment: 'moment',
      .....
    }),
    viteCommonjs(),
  ],
}),

I understand why it is not working, inject only runs on build not in the test env But I really need to have access to those globals. Is there a way to access them, or is the only way to mock all of them one by one ?

For exemple :

__ contains a lots of helpers, like classNames (under __.cn())

So i have tried to mock a global __ like :

globalThis.__ = {
  cn: (...classes) => classes.filter(Boolean).join(' '),
  i18n: {t: (s) => s},
};

But running my tests results in a TypeError: cn is not a function

2
  • "So i have tried to mock a global" - where? Commented Aug 5 at 13:48
  • You're mocking globalThis.__ as an object, but in your code you're likely calling __.cn() — implying __ is a function that returns an object, not an object itself. Commented Aug 5 at 13:57

1 Answer 1

1

Mock __ as a function that returns our helper object:

globalThis.__ = () => ({
  cn: (...classes) => classes.filter(Boolean).join(' '),
  i18n: { t: (s) => s },
});

Now __.cn() works because __() returns an object with cn.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.