angularunit-testingjestjsstackblitz

How to setup jest with angular in stackblitz


Is it possible to setup stackblitz project to run angular unit-testing with jest?

Update:

Got it working with codesandbox(it's already running on jest) but have yet not been able to make it run with stackblitz, taken in consideration they work differently.

Thanks in advance!


Solution

  • TLDR: this is my working StackBlitz project with Jest 29.7 and Angular 18.8

    Now if you want to do it yourself in your own project running on StackBlitz, or in any Angular starter, these are the steps I followed:

    1. Install jest, jest-preset-angular angular-builders/jest:

      in the console run: npm install jest jest-preset-angular @angular-builders/jest

      Note: I am not sure what angular-builders/jest is for. can this be ommitted?

    2. Create a setup-jest.ts file in the root of the project with this content:

       import 'jest-preset-angular';
      
    3. Create a jest.config.ts file in the root of the project with this content:

       module.exports = {
        rootDir: '.',
        // Other Jest configuration options...
       };
      

      Note: this rootdir should be the root directory of your project. in the StackBlitz Angular starter, this is the root folder of the running project, so the code above will work.

    4. Install npm i @types/jest --save-dev

    5. Create at least one test: Create a file src/main.spec.ts with the content:

        describe('This is the demo test', () => {
          it('should succeed', () => 
            expect(true).toEqual(true));
        });
      
    6. Open a terminal in StackBlitz and run jest.