Unit test using jest

I need to add jest unit test for enonic project.

let convertDateFormatInReverse = require('/lib/utils/common');

describe("common js file test", () => {
    test('test convertDateFormatInReverse', () => {


this gives below error

Cannot find module '/lib/utils/common' from 'src/test/resources/lib/utils/common.test.js'

  1 | let convertDateFormatInReverse = require('/lib/utils/common');
    |                                                              ^
  2 |
  3 | describe("common js file test", () => {
  4 |     test('test convertDateFormatInReverse', () => {

  at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:427:11)
  at Object.<anonymous> (src/test/resources/lib/utils/common.test.js:1:62)

It seems the js files path using enonic is different in jest since it is basically for react or node js based projects, Is there any way to resolve this issue?

I’m currently writing a guide on how to test Enonic code using Jest.

Here are the current state of it (under construction)

Luckily for you one of the examples is exactly what you need:

1 Like

If you need full asciifolding you might try installing the @enonic/js-utils npm package.

import {sanitize} from ‘@enonic/js-utils/string/sanitize’;

Here is the implementation

To fix this you need to setup paths correctly in tsconfig.json

Jest typically reads the tsconfig.json file on the project root.

If you use different tsconfig.json files for serverside and clientside, you need to tell jest which one to use.

This can be done easily on the commandline.

It can also be done with some difficulty in the jest.config.ts

1 Like

Im using JavaScript in my project. Not typeScript. DO you have an exampe for JS project?

Not really. This is not a Enonic challenge though. This is a general Jest challenge. So you should be able to use the jest documentation to create a virtual module mock: