# Angular with Jest setup

In this article, I'll show how to set up a basic Angular app with Jest. In case of any problems please refer to the official documentation:

* Jest - https://jestjs.io
    
* jest-preset-angular - https://thymikee.github.io/jest-preset-angular
    

The setup is based on Angular 15 and Jest 29. Make sure you have globally installed `Angular CLI 15` and `npx`.

# Create the app (optional)

Create the new application with the defaults using Angular CLI.

```shell
ng new app --defaults=true
```

Navigate to the app directory:

```shell
cd app
```

# Set up the Jest

Install required dependencies

```shell
npm i jest@29 @types/jest@29 jest-preset-angular ts-jest
```

Create `setup-jest.ts` file the application root and insert contents:

```typescript
import 'jest-preset-angular/setup-jest';
```

Create `jest.config.js` file in the application root and insert contents:

```javascript
module.exports = {
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
  globalSetup: 'jest-preset-angular/global-setup',
};
```

Update `tsconfig.spec.json` file to match the following contents. There are two differences between the original and the changed file:

* added `"module": "CommonJs"`
    
* changed `"types": ["jasmine"]` to `"types": ["jest"]`
    

```json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "module": "CommonJs",
    "types": ["jest"]
  },
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}
```

Remove `karma` and `jasmine` dependencies.

```shell
npm remove @types/jasmine jasmine-core karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter
```

# Verify

Use the following command to run the tests. In the default app, there is one test suite for the `AppComponent` with 3 tests.

```shell
npx jest
```

The tests were run successfully.

```text
 PASS  src/app/app.component.spec.ts
  AppComponent
    ✓ should create the app (183 ms)
    ✓ should have as title 'app' (36 ms)
    ✓ should render title (34 ms)

Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        3.577 s, estimated 5 s
Ran all test suites.
```
