Rails + Webpacker + Vue + Jestでテスト環境を作りました
とりあえず環境ができるとこまでをメモがわりに
Install
-
install jest
docker-compose run --rm app bin/yarn add jest --dev
-
babel用のライブラリを追加
docker-compose run --rm app bin/yarn add babel-jest babel-polyfill --dev
-
設定追加
-
touch
vendor/package.json
{ "jest": { "testPathDirs": ["<rootDir>/../app/javascript/packs"], "moduleDirectories": ["<rootDir>/node_modules"], "moduleFileExtensions": ["js", "vue"] } }
-
edit
package.json
... "scripts": { "test": "./node_modules/.bin/jest" }
-
とりあえずFailできるとこまで動いた
# bin/yarn test
yarn test v0.27.5
$ ./node_modules/.bin/jest
// なんか色々エラー
Test Suites: 8 failed, 8 total
Tests: 0 total
Snapshots: 0 total
Time: 13.825s
Ran all test suites.
error Command failed with exit code 1.
動作確認用のコード
// app/javascript/packs/sample.js
function sum(a, b) {
return a + b
}
module.exports = sum
// app/javascript/packs/test/sample.test.js
const sum = require('../sample.js')
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3)
})
動くようにライブラリ・設定追加
- add jest preprocessor
docker-compose run --rm app bin/yarn add jest-vue-preprocessor --dev
{
"jest": {
...
"moduleNameMapper": {
"^vue$": "vue/dist/vue.common.js"
},
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/jest-vue-preprocessor"
}
}
}
Pass!
bin/yarn test app/javascript/packs/test/
yarn test v0.27.5
$ ./node_modules/.bin/jest "app/javascript/packs/test/"
PASS app/javascript/packs/test/sample.test.js
✓ adds 1 + 2 to equal 3 (3ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.552s
Ran all test suites matching /app\/javascript\/packs\/test\//i.
Done in 37.26s.
Todo
- Vueのコンポーネントテスト
-
yarn test
にディレクトリ指定を渡さなくてもよくしたい
参考文献
https://github.com/pstjean/webpacker-jest
https://hackernoon.com/jest-for-all-episode-1-vue-js-d616bccbe186
https://facebook.github.io/jest/docs/en/webpack.html
https://alexjoverm.github.io/2017/08/21/Write-the-first-Vue-js-Component-Unit-Test-in-Jest/