During unit testing, I am getting undefined error, while executing svelte component with json file.
Restaurant.svelte :
import data from '../Data/restaurants.json';
console.log(data);
let finalData = data.restaurants;
restaurant.spec.js :
import Restaurant from './../routes/Restaurant.svelte';
import { render, screen, fireEvent } from "@testing-library/svelte";
describe("Restaurants Home Page",()=>{
it("Tests for Header",()=>{
render(Restaurant);
const resheader = screen.getByText("Restaurants");
expect(resheader).toBeVisible();
})
})
Jest Config File :
{
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.svelte$": "svelte-jester",
".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
},
"moduleFileExtensions": ["svelte", "js", "json"],
"transformIgnorePatterns": ["node_modules/(?!(svelte-spa-router|svelte-i18n)/)"],
"testEnvironment": "jsdom",
"setupFilesAfterEnv": ["@testing-library/jest-dom/extend-expect"],
"moduleDirectories": [
"node_modules",
"src"
],
"moduleNameMapper": {
"src/(.*)": "<rootDir>/src/Data"
}
}
Error Msg: TypeError: Cannot read properties of undefined (reading 'restaurants')
7 |
8 | console.log(data);
> 9 | let finalData = data.restaurants;
I highly recommend using vitest for testing SvelteKit apps as they both use vite which reduces the amount of configuration and incompatibilities.
That said, this can also work in svelte-jester by using the
* as
syntax: