Getting ParseError: Identifier is expected on importing svelte files for testing with jest

Total
1
Shares

My Jest config details are

jest.config.js

module.exports = {
    transform: {
        '^.+\.svelte$': 'svelte-jester',
        '^.+\.js$': 'babel-jest',
    },
    moduleFileExtensions: ['js', 'svelte'],
}

babel.config.js

module.exports = {
    presets: [
        [
            '@babel/preset-env',
            {
                targets: {
                    node: 'current',
                },
            },
        ],
    ],
}

package.json

  .
  .
  "@babel/core": "^7.10.2",
    "@babel/preset-env": "^7.10.2",
    "babel-jest": "^26.0.1",
    "jest": "^26.0.1",
    "svelte-jester": "^1.0.6",
    "@testing-library/svelte": "^3.0.0"
  },
  "scripts": {
    "build": "cross-env NODE_ENV=production webpack",
    "dev": "webpack-dev-server --content-base public",
    "test": "jest src",
    "test:watch": "npm run test -- --watch"
  },
  .
  .

I created src/test folder where my test.spec.js is as follows

import {fireEvent, render} from '@testing-library/svelte';

import App from '../App.svelte';

describe('test', () => {
    test('Just a mock test', async () => {
        const myMock = jest.fn();
        console.log(myMock());

        myMock.mockReturnValueOnce(10).mockReturnValueOnce('x').mockReturnValue(true);

        console.log(myMock(), myMock(), myMock(), myMock());
    });
});

Plz note that this I used a jest mock function just for testing purpose but whenever I import a svelte file as in this case App.svelte I get an error as below

FAIL src/test/test.spec.js
● Test suite failed to run

ParseError: Identifier is expected

Solution

I found a possible solution to this parsing error. Apparently, the IDE was unable to resolve certain style classes in the test.svelte file defined inside style tag, which is why it was showing up ParseError.
I would suggest anyone coming across this error to check your svelte file thoroughly for errors since svelte-testing-lib parses through the entire file before executing any test function.

Leave a Reply

Your email address will not be published. Required fields are marked *