Nuxt.jsはsrcディレクトリやrootディレクトリにエイリアスがついており、importなどではそれを使用する。
こんな感じで。
import child from '@/components/Child'
しかしjestでテストを書こうとした場合に、パスが解決出来なくてエラーになってしまう。
Cannot find module '../pages/index.vue' from 'index.test.js'
解決策
package.jsonで、jestの設定に moduleNameMapper
を追加する。
これでパスを意図したとおりに解決してくれる様になる。
"moduleNameMapper": { "^@/(.*)$": "<rootDir>/$1", "^~/(.*)$": "<rootDir>/$1" }
shallowを使う
UnitTestであればそもそもサブコンポーネントの依存を切り離してテストをした方がよい。
vue-test-utilsを使っているのであれば、shallowを使うとサブコンポーネントはスタビングされる。
import { shallow } from 'vue-test-utils' import index from '../pages/index.vue' describe('shallow sample', () => { test('shallowを使ってテスト', () => { // shallowの場合はサブコンポーネントがレンダリングされない const wrapper = shallow(index) expect(wrapper.vm.message).toEqual('Hello, shallow!') }) })