Search code examples
typescriptjestjsts-jest

Problems testing with Jest, electron and typescript


Trying to test a part of my electron app I run into the following problem:

● Test suite failed to run

    SyntaxError: Invalid or unexpected token
    
    
    >  7 | const imageSrc = require('./../../../../applications/browser-app/assets/image.png');   

Running the app, the image is available but this should not matter for my simple test. As far as I can understand the error is that the require keyword is unknown. If I remove the line with require my simple test is successful but then I have no image. Unfortunately I am quite new to the world of TS, jest and electron so I do not know which module I need additionally to get the tests to run. Here is part of my package.json:

"devDependencies": {
    "@testing-library/react": "^14.0.0",
    "@types/jest": "^26.0.20",
    "jest": "^26.6.3",
    "rimraf": "^2.7.1",
    "ts-jest": "^26.5.6",
    "ts-node": "^10.9.1",
    "typescript": "~4.5.5"
},
"scripts": {     
    "test": "jest --config configs/jest.config.ts"     
},

and here is my jest.config.ts:

import type { Config } from '@jest/types';

export default async (): Promise<Config.InitialOptions> => ({
    preset: 'ts-jest',
    testMatch: ['**.test.ts'],
    rootDir: '../',
    transform: {
        '^.+\\.(ts)$': 'ts-jest'
    }
});

and my tsconfig.json:

{
    "compilerOptions": {
        "skipLibCheck": true,
        "declaration": true,
        "declarationMap": true,
        "noImplicitAny": true,
        "noEmitOnError": false,
        "noImplicitThis": true,
        "noUnusedLocals": true,
        "strictNullChecks": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "downlevelIteration": true,
        "resolveJsonModule": true,
        "module": "commonjs",
        "moduleResolution": "node",
        "target": "ES2017",
        "jsx": "react",
        "lib": ["ES2017", "dom"],
        "sourceMap": true,
        "rootDir": "src",
        "outDir": "lib"
    },
    "include": ["src"]
}

Solution

  • I found a solution:

    The error I was encountering was because Jest doesn't know how to handle the import of a .png file. I thought it did not understand require. But Jest is a JavaScript testing framework and it does not understand how to import non-JavaScript files by default.

    To solve this, I needed to mock static file content using Jest. I had to create a mocks folder at the root of my project, then create a file inside it for each file type I wanted to mock. I created a file named fileMock.js with the following content:

    module.exports = 'test-file-stub';
    

    Then, in my jest.config.ts file, I needed to map these file types to the mock file I just created. I did this by adding a moduleNameMapper property to the config:

    import type { Config } from '@jest/types';
    
    export default async (): Promise<Config.InitialOptions> => ({
        preset: 'ts-jest',
        testMatch: ['**.test.ts'],
        rootDir: '../',
        transform: {
            '^.+\\.(ts)$': 'ts-jest'
        },
        moduleNameMapper: {
            "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/mocks/fileMock.js"
        }
    });

    With those changes my test run was successful.