programing

Jest로 테스트를 실행할 때 Vue 컴포넌트에 Trix 에디터가 마운트되지 않는 이유는 무엇입니까?

prostudy 2022. 6. 7. 21:30
반응형

Jest로 테스트를 실행할 때 Vue 컴포넌트에 Trix 에디터가 마운트되지 않는 이유는 무엇입니까?

Trix 에디터를 감싸는 간단한 Vue 컴포넌트를 만들었습니다.테스트를 작성하려고 하는데 Trix가 제대로 마운트되지 않고 브라우저처럼 툴바 요소가 생성되지 않습니다.Jest 테스트 주자를 쓰고 있어요.

트릭스 에디트표시하다

<template>
  <div ref="trix">
    <trix-editor></trix-editor>
  </div>
</template>

<script>
import 'trix'

export default {
  mounted() {
    let el = this.$refs.trix.getElementsByTagName('trix-editor')[0]
    // HACK: change the URL field in the link dialog to allow non-urls
    let toolbar = this.$refs.trix.getElementsByTagName('trix-toolbar')[0]
    toolbar.querySelector('[type=url]').type = 'text'

    // insert content
    el.editor.insertHTML(this.value)

    el.addEventListener('trix-change', e => {
      this.$emit('input', e.target.innerHTML)
    })
  }
}
</script>

TrixEdit.spec.js

import { mount, shallowMount, createLocalVue } from '@vue/test-utils'
import TrixEdit from '@/components/TrixEdit.vue'

const localVue = createLocalVue()
localVue.config.ignoredElements = ['trix-editor']

describe('TrixEdit', () => {
  describe('value prop', () => {
    it('renders text when value is set', () => {
      const wrapper = mount(TrixEdit, {
        localVue,
        propsData: {
          value: 'This is a test'
        }
      })

      expect(wrapper.emitted().input).toEqual('This is a test')
    })
  })
})

expect()에러가 발생하여 다음 오류가 발생

    Expected value to equal:
      "This is a test"
    Received:
      undefined

    at Object.toEqual (tests/unit/TrixEdit.spec.js:19:39)

테스트에서 트릭스가 초기화되지 않는 이유는 무엇입니까?

trix-editor탑재되어 있지 않은 것은 주로MutationObserver는 JSDOM 11에서 지원되지 않으며 사용되지 않았습니다.테스트에서는 아래에 설명된 다른 버그가 몇 가지 있었습니다.

GitHub 데모 (문제 수정 완료)


실종된MutationObserver그리고.window.getSelection

Vue CLI 3.7.0은 JSDOM 11을 사용하여MutationObserver를 트리거하기 위해 커스텀 요소 폴리필이 필요합니다.이 라이프 사이클 훅은 보통trix-editor의 초기화로 인해trix-toolbar테스트에서 쿼리하려고 하는 요소.

해결책 1: 테스트에서 다음 날짜 이전에 Import합니다. TrixEdit.vue, 및 stubwindow.getSelection(호출자)trix현재 JSDOM에서는 지원되지 않습니다).

import 'mutationobserver-shim' // <-- order important
import TrixEdit from '@/components/TrixEdit.vue'

window.getSelection = () => ({})

해결책 2: 에 의해 설정된 Jest 셋업 스크립트로 위의 작업을 수행합니다.

  1. 의 구성 개체에 다음 속성을 추가합니다.jest.config.js(또는jestpackage.json):
setupTestFrameworkScriptFile: '<rootDir>/jest-setup.js',
  1. 다음 코드를 에 추가합니다.<rootDir>/jest-setup.js:
import 'mutationobserver-shim'
window.getSelection = () => ({})

실종된attachToDocument

@vue/test-utils는 기본적으로 문서에 요소를 첨부하지 않습니다.trix-editor를 잡지 못한다.connectedCallback초기화에 필요합니다.

솔루션:장착할 때 옵션 사용TrixEdit:

const wrapper = mount(TrixEdit, {
  //...
  attachToDocument: true, // <-- needed for trix-editor
})

에 대한 조기 참조trix-editor의 에디터

TrixEdit잘못 추측하다trix-editor마운트 시 즉시 초기화되지만 초기화가 보장되지 않는 한trix-initialize이벤트, 액세스trix-editor님의 내부 에디터는undefined언급.

솔루션:이벤트 핸들러를 추가합니다.trix-initialize이전 초기화 코드를 호출하는 이벤트mounted():

<template>
  <trix-editor @trix-initialize="onInit" />
</template>

<script>
export default {
  methods: {
    onInit(e) {
      /* initialization code */
    }
  }
}
</script>

수신기 변경 전에 설정된 값

초기화 코드는trix-change값이 이미 설정된 후 이벤트 트리거가 누락됨첫 번째 초기값 설정도 검출하여 재검출하는 것이 목적이었던 것 같습니다.input이벤트입니다.

해결책 1: 먼저 이벤트청취자를 추가합니다.

<script>
export default {
  methods: {
    onInit(e) {
      //...
      el.addEventListener('trix-change', /*...*/)

      /* set editor value */
    }
  }
}
</script>

해결책 2: 사용v-on:trix-change="..."(또는@trix-change위의 셋업 순서의 문제가 해소됩니다.

<template>
  <trix-editor @trix-change="onChange" />
</template>

<script>
export default {
  methods: {
    onChange(e) {
      this.$emit('input', e.target.innerHTML)
    },
    onInit(e) {
      //...
      /* set editor value */
    }
  }
}
</script>

값 설정으로 인해 오류가 발생함

초기화 코드는 다음과 같은 코드로 편집기 값을 설정합니다. 테스트에서 오류가 발생합니다.

el.editor.insertHTML(this.value) // causes `document.createRange is not a function`

솔루션:사용하다trix-editor의 »value이accessor: " " " " " " " " " " " accessor " 。

el.value = this.value

는 상상에 포함된 이지 않은 할 수 .trix, 에러 lib를 할 수 요. 폴리필을 강제로 적용하는 실험을 해봤는데, 그러면 같은 오류를 재현할 수 있어요.TypeError: Cannot read property 'querySelector' of undefined크롬 브라우저 환경에서도 사용할 수 있습니다.

자세히 조사하면, 그 .MutationObserver행동 차이는 있지만 아직 진상을 파악하지 못하고 있습니다.

재생 방법:

트릭스 에디트표시하다

<template>
  <div ref="trix">
    <trix-editor></trix-editor>
  </div>
</template>

<script>

// force apply polymer polyfill
delete window.customElements;
document.registerElement = undefined;

import "trix";

//...

</script>

언급URL : https://stackoverflow.com/questions/55907211/why-wont-trix-editor-mount-in-vue-component-when-running-tests-with-jest

반응형