Unit Testing with Typescript

System Information
  • Strapi Version: 4.4.5
  • Operating System: Mac and Linux
  • Database: Postgres
  • Node Version: 16
  • NPM Version: 8
  • Yarn Version: 1.22

Hey there, I have run into some problems unit testing our Strapi instance with Typescript and I’m wondering if anyone has found a good config that might overcome these problems. Right now I’m using ts-jest to run tests that are written in TypeScript. Following the Jest setup guide in the Strapi docs, I have an initializer that creates the Strapi instance and I have added the strapi.compile() step that is required for TypeScript. However I have run into the following issues:

Mocking
Since the compile step turns all the TypeScript code into JavaScript in a dist/ folder, I haven’t been able to setup mocks for the project files (mocks for npm packages work fine). If I try to jest.mock() a module in src it just doesn’t pick up the mock (I assume since Strapi is running from dist/). If I try to mock the file in dist/, ts-jest errors with something like: “Unable to process [test file] please make sure that outDir in your tsconfig is neither '' or '.'. You can also configure Jest config option transformIgnorePatterns to inform ts-jest to transform [test file]”. This happens even if a put the compile step into the Jest’s globalSetup file which runs before the enviroment is setup.

Relative Paths
We have a directory of HTML templates that we use for emails and I would like to be able to do unit testing on the functions that create the emails. These are tests that don’t require HTTP requests against the server, so it’s more of a true unit test of the source code. If I import them from src the paths to the email templates are not found since our TS code thinks it’s running from dist and it puts an extra ‘…’ in the path. If I import the email code from dist I get the same error above from ts-jest.

Coverage
If I try to run a coverage report on the src directory it doesn’t work because that code is not executed (only the one in dist). If I run the coverage report on dist/src that works, but it’s against the transpiled code and the reporting is not accurate at all.

Can anyone suggest a workaround for some of these issues? I imagine there could be a solution that involves running the tests from the dist/ directory after they are transpiled, but it appears it would require running strapi.compile() in a script before jest even starts to execute. And I imagine there would be an issue with the output not showing correct line numbers because it would be running the tests as already transpiled code. Perhaps there’s a way to compile Strapi with source maps and configure Jest to use those? If anyone has any suggestions I would be most appreciative.

Thanks so much!

Tim