I have a new Vite project with Svelte and Typescript and I am trying to integrate it with Vitest to start writing unit tests. However when running npm test
I am getting the following error:
FAIL src/util.test.ts [ src/util.test.ts ]
SyntaxError: Named export 'setCancelSyntheticClickEvents' not found. The requested module '@polymer/polymer/lib/utils/settings.js' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from '@polymer/polymer/lib/utils/settings.js';
const { setCancelSyntheticClickEvents } = pkg;
File that is being tested - util.ts:
import '@vaadin/notification'
export const sum = (item1: number, item2: number): number => {
return item1 + item2
}
Unit test file - util.test.ts:
import { describe, test, expect } from 'vitest'
import { sum } from './util'
test('123', () => {
expect(sum(1, 1)).toBe(2)
})
Vitest config - vitest.config.ts:
import { defineConfig } from 'vitest/config'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import commmonjs from '@rollup/plugin-commonjs'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [svelte(), commmonjs()],
test: {
globals: true,
}
}
})
Package json:
{
"name": "svelte-ts",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"test": "vitest",
"preview": "vite preview",
"check": "svelte-check --tsconfig ./tsconfig.json"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^25.0.5",
"@sveltejs/vite-plugin-svelte": "^2.4.2",
"@tsconfig/svelte": "^5.0.0",
"@vitest/ui": "^0.34.6",
"svelte": "^4.0.5",
"svelte-check": "^3.4.6",
"tslib": "^2.6.0",
"typescript": "^5.0.2",
"vite": "^4.4.5",
"vite-plugin-babel": "^1.1.3",
"vitest": "^0.34.6"
},
"dependencies": {
"@vaadin/notification": "^24.2.0"
}
}
I am certain that it is the import for vaadin/notification in the sum.ts
file because when I comment it out the tests pass.
From the error it seems like there is a conflict between using CommonJS modules and ES6 imports in this @vaadin/notification package.
- I've tried reading parts of the documentation on vite and vitest to set up these configuration files.
- Due to the conflict I've tried adding the CommonJS pluging to the
vitest.config.ts
. I was hoping it would transform the older commonjs module. - I've also tried adding the
babel
plugin to thevitest.config.ts
but this didn't change the error
Any suggestions would be appreciated thank you.