Wednesday, 26 January 2022

Jest throw error when I write test using TypeScript syntax

I have error on my test.ts file,

Module parse failed: Unexpected token

File was processed with these loaders:
./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
./node_modules/babel-loader/lib/index.js
You may need an aaadditional loader to handle the result of these loaders.

describe('FormDataAccess`, () => {
  test('Something', () => {
    const formData: FormData = {
      ......
    }
    ......
    expect(ABC).toEquaal(A.B?.C);
})
}

If I remove the :FormData and remove the ? , it will compile successfully.

This is my Jest Config file:

module.exports = {
    preset: 'ts-jest',
    setupFilesAfterEnv: ['./jest.setup.ts'],
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
    testPathIgnorePatterns: ['node_modules/', '/src/i18n/__tests__', 'dist/', 'build/'],
    transform: {
        '^.+\\.tsx?$': 'ts-jest',
        '^.+\\.(js|jsx)$': 'babel-jest'
    },
    transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$', '^.+\\.module\\.(css|sass|scss)$'],
    testMatch: ['**/*.(test|spec).(js|ts|tsx)'],
    moduleDirectories: ['node_modules', 'src'],
    moduleNameMapper: {
        '\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': 'identity-obj-proxy',
        '\\.(css|less|scss|sass)$': 'identity-obj-proxy'
    },
    roots: ['<rootDir>', 'src', 'node_modules'],
    modulePaths: ['<rootDir>'],
    clearMocks: true,
    collectCoverage: true,
    collectCoverageFrom: ['src/**/*.{ts,tsx}', '!**/*.stories.{ts,tsx}', '!src/index.ts', '!**/node_modules/**'],
    coverageDirectory: './build/brazil-documentation/coverage',
    coverageReporters: ['json-summary', 'text', 'html', 'cobertura']
};

This is my WebPack config file's rule:

module: {
    rules: [
        {
            // Include ts, tsx, js, and jsx files.
            test: /\.(ts|js)x?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            options: {
                babelrc: true
            }
        },
        {
            test: /\.(png|jpe?g|gif|bmp|svg)$/,
            use: 'url-loader'
        },
        {
            test: /\.css$/i,
            use: ['style-loader', 'css-loader']
        }
    ]
},

Can someone guide me how can I resolve this error, what is a must have in my Jest or webpack config file?

Thanks!



from Jest throw error when I write test using TypeScript syntax

No comments:

Post a Comment