Cypressでunit-testをやるメリット
vue-test-utilsはbrowser APIをスタブ化して実行するが、Cypress Vue Unit Testは本物のブラウザーで実行される
インスト-ル
npm i -D cypress cypress-vue-unit-test cypress-nuxt
https://www.cypress.io/
https://github.com/bahmutov/cypress-vue-unit-test
https://github.com/NickBolles/cypress-nuxt
設定
cypress.json
{
"$schema": "https://raw.githubusercontent.com/cypress-io/cypress/develop/cli/schema/cypress.schema.json",
"pluginsFile": "./test/component/plugins/index.js",
"experimentalComponentTesting": true,
"componentFolder": "test/component/integration",
"testFiles": "**/*.js"
}
text/component/plugins/index.js
const cypressNuxt = require("cypress-nuxt");
const path = require('path')
module.exports = async (on, config) => {
return cypressNuxt
.plugin({
loadOptions: {
rootDir: path.join(__dirname, '../../..')
}
})
.then(function(webpackPreProcessor) {
on('file:preprocessor', webpackPreProcessor)
return config
})
};
cypress-nuxt入れずに自前でやる人はこの辺りを参考に
https://github.com/bahmutov/cypress-vue-unit-test/issues/200
テストファイルの作成
index.spec.js
/// <reference types="Cypress" />
import { mountCallback } from 'cypress-vue-unit-test'
import Index from '../../../pages/index.vue'
import Vue from 'vue'
import Vuex from 'vuex'
import VueI18n from 'vue-i18n'
import en from '../../../locales/en.json'
import ja from '../../../locales/ja.json'
import { state, getters, mutations, actions } from '../../../store/todo'
import bootstrap from '../../../node_modules/bootstrap/dist/css/bootstrap.min.css'
Vue.use(Vuex)
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'en',
messages: {
en,
ja
}
})
const store = new Vuex.Store({
modules: {
todo: {
namespaced: true,
state,
getters,
actions,
mutations
}
}
})
Vue.prototype.$store = store
const extensions = {
filters: {},
plugins: [],
mixins: []
}
describe('Index', () => {
const template = `
<div v-if="flag">
<Index />
</div>
`
function data() {
return { flag: false }
}
const components = { Index }
beforeEach(
mountCallback(
{ template, data, components },
{ extensions, i18n, cssFiles: [bootstrap] }
)
)
describe('test', () => {
beforeEach(() => {
Cypress.vue.flag = true
})
afterEach(() => {
Cypress.vue.flag = false
})
it('', () => {
cy.log(Cypress.vue)
cy.get('h1')
})
})
})
直接mount
コンポーネントを直接mountもできるが、テスト後にdestroyされないので、次のテスト時も残る。
Cypress.vue.$destroy() でdestroy処理は動かせるがコンポーネントはしなない
import { mount } from 'cypress-vue-unit-test'
describe('test', () => {
beforeEach(mount(Index, { extensions, i18n, cssFiles: [bootstrap] }))
なのでmountは一回だけにしてCypress.vueでcomponentのdataになっているため直接代入してクリアもできるがdataが多いとめんどう
⇒ コンポーネントを自動的に削除してcreateからやり直してくれる何かやり方があるのでしょうか?
クリア例
afterEach(() => {
Cypress.vue.text = ''
Cypress.vue.users = []
})
it('mount', () => {
mount(Index, { extensions, i18n, cssFiles: [bootstrap] })
})
it('2', () => {
cy.get('h1')
})