これからはじめるVue.js実践入門
posted with ヨメレバ
山田 祥寛 SBクリエイティブ 2019年08月23日頃    
テスト
単体テスト
Jestの準備
1. Vue CLIのJestプラグインの導入
- npx vue create xxxでのプロジェクト作成時にUnit Testingを有効にし、テストライブラリとしてJestを選択する。
 (既存のプロジェクトにはnpx vue add @vue/cli-plugin-unit-jestで追加する)
- Vue CLIでJestプラグインを有効にすると、Vueのテストに必要な@vue/test-utilsパッケージもインストールされる。
- Jestを有効にすると、tests/unit/example.spec.jsとjest.configが生成される。
 jest.configを編集して設定を変更することもできるが、Jestは何もせずにそのまま実行可能でそれがメリットでもある。
2. テストコード作成
describe('Jestの基本', () => {
  beforeEach(()=>
    console.log(new Date().toLocaleString())
  )
  it('初めてのテスト', () => {
    expect(1+1).toBe(2);
  })
})3. テスト実行
- npm run test:unit
 (npx vue-cli-service test:unitが実行される)
Matcher
- Matcher(アサーションメソッド)はtoBe以外にもたくさんある。
 https://jestjs.io/ja/docs/using-matchers
- 否定を表現する場合はnotメソッドを使う。expect(1+1).not.toBe(2);
コンポーネントのテスト
- デフォルトで生成されるexample.spec.jsは以下のソースとなっている。
import { shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'
describe('HelloWorld.vue', () => {
  it('renders props.msg when passed', () => {
    const msg = 'new message'
    const wrapper = shallowMount(HelloWorld, {
      propsData: { msg }
    })
    expect(wrapper.text()).toMatch(msg)
  })
})- shallowMountメソッドとテスト対象コンポーネントのインポートを行う。
- shallowMountでコンポーネントを描画(マウント)する。
- 第2引数にpropsData,attrsなどを渡す。
- 戻り値のWrapperインスタンスはコンポーネントを取得・テストするためのメソッドを持っている。
 https://v1.test-utils.vuejs.org/ja/api/wrapper/
 セレクタで要素を指定できるfind, findAllメソッドがよく使われる。- h1のテキストを取得: wrapper.find('h1').text()
- テキストボックスに入力: wrapper.find('#name').setValue('abc')
- フォーム送信: wrapper.find('form').trigger('submit.prevent')
 
- h1のテキストを取得: 
- setPropsメソッドを使うと、マウントした後でもプロパティを変更することができる。await wrapper.setProps({msg: 'ほげ'})
 ※関数をasync () => {とする必要あり
 
mountメソッドとshallowMountメソッド
- 子コンポーネントの描画に違いがある。
- mountメソッドではそのまま描画されるが、shallowMountメソッドの場合はスタブが使われる。
- 親コンポーネントは子コンポーネントに依存するべきではないなので、通常はshallowMountメソッドを使う。
 (子コンポーネントとの連携に着目したいときだけmountメソッドを使う)
<template>
  <HogeHoge></HogeHoge>
</template><template>
  <h2>HogeHoge</h2>
</template>import { shallowMount, mount } from '@vue/test-utils'
// 〜省略〜
const wrapper1 = shallowMount(App)
const wrapper2 = mount(App)
console.log(wrapper1.html()); // <hogehoge-stub></hogehoge-stub>
console.log(wrapper2.html()); // <h2>HogeHoge</h2>算出プロパティのテスト
- callメソッドでthisに割り当てるオブジェクトを渡す。 expect(MyComponent.computed.hoge.call({name: '123'})).toBe('abc')
data: function () {
  return {
    name: ''
  }
},
computed: {
  hoge() {
    return this.name.toLowerCase()
  }
}Vuexを使っている場合
- Wrapperインスタンス.vm.xxxでアクセス可能。
import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import App from '@/App.vue'
import store from '@/store/index'
const localVue = createLocalVue()
localVue.use(Vuex)
// 〜省略〜
const wrapper = shallowMount(App, {store, localVue})
expect(wrapper.vm.count1).toBe(0)E2Eテスト
E2Eテストとは
- End to Endテストはユーザーの操作をシミュレートし、リリース前の最終的な動作確認を行うためのテスト。
- シナリオテスト、インテグレーションテストとも呼ばれる。
Nightwatch
- Vue CLIではnpx vue create xxxでのプロジェクト作成時にManually select featuresを選択し、テストライブラリとしてNightwatchを選択する。
 (既存のプロジェクトにはnpx vue add @vue/cli-plugin-e2e-nightwatchで追加する)
- Nightwatchを有効にすると、tests/e2e/spec/test.jsにサンプルコードが生成される。
- テストケースに渡される引数browserはNightwatchインスタンスであり、ブラウザ操作や検証用のメソッドを提供する。
 https://nightwatchjs.org/api/
- npm run test:e2eでテストが実行される。
 (npx vue-cli-service test:e2eが実行される)
module.exports = {
  'default e2e tests': browser => {
    browser
      .init()
      .waitForElementVisible('#app')
      .assert.elementPresent('.hello')
      .assert.containsText('h1', 'Welcome to Your Vue.js App')
      .assert.elementCount('img', 1)
      .end()
  },
}- ブラウザ操作はbrowser.xxx()だが検証はbrowser.assert.xxx()となる。
 ※ assertとは別にexpectアサーションも用意されている。browser.expect.element('#name').to.be.attribute('class').contains('hoge')
 #nameの要素がclass="hoge"を持っているかどうか。
 toやbeはソースを英文のように読みやすくするためだけのもので、何も意味は持たない。

