この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
どうも!大阪オフィスの西村祐二です。
最近、Reactでよく使われるテストフレームワーク「Jest」が良さそうだったのでAngularでも使いたいなと思っていました。
下記のライブラリを使えば簡単にAngular+Jestの構成にすることができましたので、ご紹介したいと思います。
https://github.com/briebug/jest-schematic
環境
Angular CLI: 7.2.2
Node: 10.15.0
OS: darwin x64
Angular:
...
Package Version
------------------------------------------------------
@angular-devkit/architect 0.12.2
@angular-devkit/core 7.2.2
@angular-devkit/schematics 7.2.2
@schematics/angular 7.2.2
@schematics/update 0.12.2
rxjs 6.3.3
typescript 3.2.2
設定方法
はやくJestを動くようにしたいという方は下記コマンドを実行して終わりです。
コマンドの意味などは、リポジトリのREADME.md等を確認してください。
$ npm install -g @briebug/jest-schematic
$ ng g @briebug/jest-schematic:add
$ ng add @briebug/jest-schematic
※注意点として、Karmaの設定ファイルなどは置きかわるので、既存のプロジェクトで実施する場合は事前検証等を行ってください。
動作確認
上記で設定は完了したので、実際にJestを動かしたいと思います。
yarn test
コマンドで実施できます。
今までng test
を使っていた方は、これからyarn test
を使うようにしましょう。
$ yarn test
yarn run v1.3.2
(node:8152) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
$ jest
● Deprecation Warning:
Option "setupTestFrameworkScriptFile" was replaced by configuration "setupFilesAfterEnv", which supports multiple paths.
Please update your configuration.
Configuration Documentation:
https://jestjs.io/docs/configuration.html
PASS src/app/app.component.spec.ts
AppComponent
✓ should create the app (134ms)
✓ should have as title 'jest-test' (48ms)
✓ should render title in a h1 tag (96ms)
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 5.709s
Ran all test suites.
✨ Done in 7.35s.
問題なく動きましたね。
ただ、警告がでているので修正しておきましょう。
setupTestFrameworkScriptFile
をsetupFilesAfterEnv
に変えてArray型に修正します。
jest.config.js
// https://github.com/thymikee/jest-preset-angular#brief-explanation-of-config
module.exports = {
preset: 'jest-preset-angular',
roots: ['src'],
setupFilesAfterEnv: [
'<rootDir>/src/setup-jest.ts'
],
moduleNameMapper: {
'@app/(.*)': '<rootDir>/src/app/$1',
'@assets/(.*)': '<rootDir>/src/assets/$1',
'@core/(.*)': '<rootDir>/src/app/core/$1',
'@env': '<rootDir>/src/environments/environment',
'@src/(.*)': '<rootDir>/src/src/$1',
'@state/(.*)': '<rootDir>/src/app/state/$1',
},
transformIgnorePatterns: ['node_modules/(?!(jest-test))'],
};
これで、警告も解消され、Jestでテストすることができます。
さいごに
いかがだったでしょうか。
Reactでよく使われるテストフレームワーク「Jest」をAngularで使えるようにしてみました。
今までReactでJestを使っていた方は、そこで培われた知見を活かせるのではないでしょうか。
誰かの参考になれば幸いです。