Angular Cli でプロジェクトを作成すると Karma + Jasmine が単体テストとして入るため
Jest に変更する手順を備忘録として残しておく
構築環境
Angular CLI: 7.3.9
Node: 10.15.3
OS: darwin x64
Angular:
...
Package Version
------------------------------------------------------
@angular-devkit/architect 0.13.9
@angular-devkit/core 7.3.9
@angular-devkit/schematics 7.3.9
@schematics/angular 7.3.9
@schematics/update 0.13.9
rxjs 6.3.3
typescript 3.2.4
手順
1. プロジェクトを作成
$ ng new JEST-EXAMPLE --style=styl
? Would you like to add Angular routing? Yes
2. 以下のコマンドを実行する
yarn global add @briebug/jest-schematic
ng g @briebug/jest-schematic:add
ng add @briebug/jest-schematic
3. 以下のコマンドを実行して動作確認する
$ yarn test
$ jest
PASS src/app/app.component.spec.ts
AppComponent
✓ should create the app (89ms)
✓ should have as title 'JEST-EXAMPLE' (28ms)
✓ should render title in a h1 tag (29ms)
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 3.913s
Ran all test suites.
✨ Done in 4.76s.
上記だけでも動くが snapshot テストを行うためには以下が追加で必要
4. src/app/app.component.spec.ts を修正
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent,
],
}).compileComponents();
}));
describe('snapshots', () => {
it('正しく render されること', () => {
const fixture = TestBed.createComponent(AppComponent);
expect(fixture).toMatchSnapshot();
});
});
});
5. src/tsconfig.spec.json を修正
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc spec",
"types": [
"jasmine", //=> "jest"
"node"
],
"module": "commonjs"
},
"files": [
"polyfills.ts"
],
"include": [
"**/*.spec.ts",
"**/*.d.ts"
]
}
6. src/angular.json から以下を削除
{
・・・
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"styles": [
"src/styles.styl"
],
"scripts": [],
"assets": [
"src/favicon.ico",
"src/assets"
]
}
},
・・・
}
7. 以下のコマンドを実行する
yarn remove @types/jasmine @types/jasminewd2
yarn add @types/jest
8. 以下のコマンドを実行して動作確認する
$ jest
PASS src/app/app.component.spec.ts
AppComponent
snapshots
✓ 正しく render されること (109ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 1 passed, 1 total
Time: 1.711s, estimated 3s
Ran all test suites.
✨ Done in 2.43s.