撰寫 Vue 的測試時,遇上要取得用 transition-group 包裹的內容。這邊筆記下取得的方式。
內容
由於動畫效果是需要計時的,所以要善用 Jest 所提供的 jest.useFakeTimers(),並執行
jest.runAllTimers() 後再通知 Vue 進行畫面更新。如此一來就可以取得 <transition group> 裡的內文了。
程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
import { nextTick } from "vue" import { mount, VueWrapper } from "@vue/test-utils" import { ElForm, ElFormItem, ElInput, ElCol, ElRow, } from "element-plus" import Form from "../Form.vue" describe("When a 'Form' is mounted", () => { let mountInstance: VueWrapper<any> const findTargetComponent = (className: string) => mountInstance.findComponent(className) beforeEach(async () => { const mountConfig = { props: { value: { userId: "userId1", }, originalValue: { userId: "userId1", }, formItems: [ { type: "input", prop: "userId", labelKey: "glossary.userId", disabled: true, }, { type: "input", prop: "name", labelKey: "glossary.name", required: true, }, ], formRules: { name: [ { required: true, min: 5, max: 10, message: "glossary.required", trigger: "blur", }, ], }, }, global: { plugins: [ElForm, ElFormItem, ElInput, ElCol, ElRow], }, } mountInstance = mount(Form, mountConfig) jest.useFakeTimers() }) afterEach(async () => { mountInstance.unmount() jest.clearAllTimers() }) describe("Form Input Error Scenarios", () => { test("Given an invalid input value, and an error message should appear.", async () => { const nameInput = findTargetComponent(".base-form-item-input-name").get( "input" ) const consoleWarnSpy = jest .spyOn(console, "warn") .mockImplementation(() => {}) await nameInput.trigger("focus") await nameInput.setValue("abc") await nameInput.trigger("blur") jest.runAllTimers() // execute to show the content in <transition-group> await nextTick() expect(nameInput.isVisible()).toBe(true) expect(nameInput.element.value).toBe("abc") expect( mountInstance .find(".is-error.is-required .base-form-item-input-name") .exists() ).toBe(true) expect( mountInstance.find(".is-error.is-required .el-form-item__error").text() ).toBe("glossary.required") expect(consoleWarnSpy).toBeCalled() }) }) }) |