簡體   English   中英

Vue.js單元測試ErrorBoundary

[英]Vue.js unit testing ErrorBoundary

我已經在Vue.js中為我的項目構建了簡單的ErrorBoundary組件,並且正在努力為其編寫單元測試。 組件的代碼如下:

<template>
  <div class="overvue-error-boundary">
    <slot v-if="!error" />
    <div class="error-message" v-else>Something went horribly wrong here.</div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      error: false
    }
  },
  errorCaptured (error, vm, info) {
    this.error = true;
  }
}
</script>

我創建了一個ErrorThrowingComponent,它在created()生命周期掛鈎上拋出一個錯誤,因此我可以測試ErrorBoundary:

const ErrorThrowingComponent = Vue.component('error-throwing-component', {
  created() {
    throw new Error(`Generic error`);
  },
  render (h) {
    return h('div', 'lorem ipsum')
  }
});

describe('when component in slot throws an error', () => {
  it('renders div.error-message', () => {
  // this is when error is when 'Generic error' is thrown by ErrorThrowingComponent
  const wrapper = shallowMount(OvervueErrorBoundary, {
    slots: {
      default: ErrorThrowingComponent
    }});
    // below code is not executed
    expect(wrapper.contains(ErrorThrowingComponent)).to.be.false;
    expect(wrapper.contains('div.error-message')).to.be.true;
  });
});

問題在於,當我嘗試實際安裝它時,ErrorThrowingComponent會引發錯誤(從而使整個測試失敗)。 有什么辦法可以防止這種情況的發生?

編輯:我試圖做到的,是在ErrorBoundary組件的默認插槽實際安裝 ErrorThrowing組件斷言,如果ErrorBoundary將呈現錯誤信息,而不是插槽。 這是我首先創建ErrorThrowingComponent的方式。 但是我無法斷言ErrorBoundary的行為,因為嘗試創建包裝器時出現錯誤。

對於在這里遇到類似問題的任何人:我已經在Discord上Vue Land的#vue-testing頻道上提出了這個問題,他們建議將整個錯誤處理邏輯移到將從errorCaptured()鈎子調用的函數中,然后然后只需測試此功能。 這種方法對我來說似乎很明智,因此我決定將其發布在這里。

重構的ErrorBoundary組件:

<template>
  <div class="error-boundary">
    <slot v-if="!error" />
    <div class="error-message" v-else>Something went horribly wrong here. Error: {{ error.message }}</div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      error: null
    }
  },
  methods: {
    interceptError(error) {
      this.error = error;
    }
  },
  errorCaptured (error, vm, info) {
    this.interceptError(error);
  }
}
</script>

使用vue-test-utils進行單元測試:

describe('when interceptError method is called', () => {
  it('renders div.error-message', () => {
    const wrapper = shallowMount(OvervueErrorBoundary);
    wrapper.vm.interceptError(new Error('Generic error'));
    expect(wrapper.contains('div.error-message')).to.be.true;
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM