Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Testing Vue components with Jest and vue-test-u...

Testing Vue components with Jest and vue-test-utils

How to test Vue components effectively with Jest and vue-test-utils.

Ryo Hashimoto

April 25, 2018
Tweet

More Decks by Ryo Hashimoto

Other Decks in Technology

Transcript

  1. Vueίϯϙʔωϯτͷྫ <template> <p>{{ greeting }} World!</p> </template> <script> module.exports =

    { data () { return { greeting: 'Hello' } } } </script> JavaScript
 (ES6) HTML
  2. Vuex ετΞͷྫ const store = new Vuex.Store({ state: { count:

    0 }, mutations: { increment (state) { state.count++ } } }) εςʔτ
 ύϥϝʔλ ϛϡʔςʔγϣϯ
 ૢ࡞
  3. Vueίϯϙʔωϯτͷ3A (1) Vue component Vuex state HTML • Vueίϯϙʔωϯτʹ VuexεςʔτΛೖྗͱ

    ͯ͠༩͑Δ͜ͱͰɺHTMLΛग़ྗ͢Δ • Arrange: VuexεςʔτɺAct: Vueίϯϙʔω ϯτɺAssert: HTML
  4. Vueίϯϙʔωϯτͷ3A (2) Vue component Vuex state HTML Event • ΠϕϯτΛ༩͑ͨ৔߹ʢΫϦοΫͳͲʣ

    • Arrange: Vuexεςʔτ, Act: Πϕϯτ / Vueί ϯϙʔωϯτ, Assert: HTML / Vuexεςʔτ
  5. Jestͷίʔυྫ // sum.js function sum(a, b) { return a +

    b } module.exports = sum // sum.test.js import sum from './sum' test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3) });
  6. wrapper (vue-test-utils) • ίϯϙʔωϯτͱԾ૝ DOM Λςετ͢Δϝ ιουΛؚΉΦϒδΣΫτ • mount /

    shallowϝιουͰίϯϙʔωϯτΛ ࢦఆͯ͠ɺॳظԽ͢Δ • wrapper.findͰDOMΤϨϝϯτΛࢦఆͯ͠ɺ triggerͰΠϕϯτΛൃՐͤ͞Δ͜ͱ͕Մೳ
  7. vue-test-utilsΛ༻͍ͨྫ test('close the app', () => { // Arrange const

    wrapper = shallow(TriggerButton) // Act wrapper.find('.close').trigger('click') // Assert expect(store.state.closed).toBe(true) })
  8. ύοέʔδͷΠϯετʔϧ • yarn add @vue/test-utils jest vue- jest babel-jest jest-serializer-

    vue --dev • jest.config.jsʹઃఆϑΝΠϧΛ௥Ճ • Rails 5.1ͷϓϩδΣΫτͰWebpackerΛ࢖༻ ͍ͯ͠ΔͷͰɺ༰қʹಋೖͰ͖ͨɻ
  9. jest.config.js module.exports = { "moduleFileExtensions": [ "js", "json", "vue" ],

    "moduleNameMapper": { "^@/(.*)$": "<rootDir>/app/javascript/$1" }, "transform": { ".*\\.(vue)$": "<rootDir>/node_modules/vue-jest", "^.+\\.js$": "<rootDir>/node_modules/babel-jest" }, "snapshotSerializers": [ "<rootDir>/node_modules/jest-serializer-vue" ], "testRegex": "/app/javascript/test/.*\\.test\\.js$" }