Reputation: 1524
I'm trying to use Jest to test my Svelte project, and everything I've read says that I need to include svelte-jester to transform my Svelte code into something that Jest can process (CommonJS, I think?). This seems to work fine, except that I'm importing Lodash into some of my Svelte components but Jest, when running its tests, is reporting that Lodash is undefined. (In a browser environment, everything seems to be working as expected.)
To demonstrate the issue, I copied and slightly modified an example from the testing-library website:
// Comp.svelte
<script>
import _ from 'lodash';
export let name
</script>
<h1>Hello {_.toUpper(name)}!</h1>
and then my test file is
// tests/Comp.test.js
import '@testing-library/jest-dom/extend-expect'
import { render } from '@testing-library/svelte'
import Comp from '../Comp'
test('shows proper heading when rendered', () => {
const { getByText } = render(Comp, { name: 'World' })
expect(getByText('Hello WORLD!')).toBeInTheDocument()
})
The relevant part of my package.json is the following, which I also got from the testing-library website.
{
"devDependencies": {
"@babel/core": "^7.12.16",
"@babel/preset-env": "^7.12.16",
"@rollup/plugin-commonjs": "^16.0.0",
"@rollup/plugin-node-resolve": "^10.0.0",
"@testing-library/jest-dom": "^5.11.9",
"@testing-library/svelte": "^3.0.3",
"babel-jest": "^26.6.3",
"jest": "^26.6.3",
"rollup": "^2.3.4",
"rollup-plugin-svelte": "^7.0.0",
"svelte": "^3.0.0",
"svelte-jester": "^1.3.0"
},
"dependencies": {
"lodash": "^4.17.20",
},
"jest": {
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.svelte$": ["svelte-jester", { "debug": true }]
},
"moduleFileExtensions": [
"js",
"svelte"
],
}
}
The test output indicates that, in the compiled version of Comp.svelte
, Lodash is undefined:
TypeError: Cannot read property 'toUpper' of undefined
5 | </script>
6 |
> 7 | <h1>Hello {_.toUpper(name)}!</h1>
| ^
at create_fragment (src/Comp.svelte:7:14)
at init (node_modules/svelte/internal/index.js:1489:37)
at new Comp (src/Comp.svelte:83:3)
at render (node_modules/@testing-library/svelte/dist/pure.js:81:21)
at Object.<anonymous> (src/tests/Comp.spec.js:9:25)
The compiled version of the component seems to indicate that, at a minimum, Lodash is being require
-d into the build.
/* Comp.svelte generated by Svelte v3.31.0 */
"use strict";
const { SvelteComponentDev, add_location, append_dev, detach_dev, dispatch_dev, element, flush, init, insert_dev, noop, safe_not_equal, set_data_dev, text, validate_slots } = require("svelte/internal");
const { default: _ } = require("lodash");
const file = "Comp.svelte";
// etc.
Can someone please tell me what I need to do to get Lodash to be properly exported and/or required into the build for a Jest test? Thank you very much.
Upvotes: 3
Views: 1851