【问题标题】:How to make unit test "location.href" by jest Vue.js如何通过 jest Vue.js 制作单元测试“location.href”
【发布时间】:2021-03-26 03:34:11
【问题描述】:

我想做什么

我想做通过点击重定向的测试。 如果可能的话,我不仅要测试称为断言的方法,还要测试重定向“URL”断言。

测试目标代码

<p class="target" v-on:click="redirect">Click!</p>

<script>
export default {
  methods: {
    redirect() {
      window.location.href = '/home'
    },
  }
}

测试代码

import { shallowMount } from '@vue/test-utils'
import redirectComponent from '../components/RedirectComponent.vue'

describe('Redirect component', () => {
  const wrapper = shallowMount(redirectComponent)

  it('Redirect By Click Test', () => {
    wrapper.find('.target').trigger('click');
    expect(window.location.href).toEqual('/home');
  })
})

结果

Expected: "/home"
Received: "http://localhost/"

如何进行重定向测试?

【问题讨论】:

    标签: vue.js jestjs


    【解决方案1】:

    window.location.href 为您提供当前页面的 URL;

    window.location.pathname 会给你当前页面的路径名,我相信这就是你要找的。​​p>

    【讨论】:

    • 感谢您的帮助。从 href 更改为路径名后,我收到了/。我期待/home
    【解决方案2】:

    这是我的解决方案!

    import { shallowMount } from '@vue/test-utils'
    import redirectComponent from '../components/RedirectComponent.vue'
    
    describe('Redirect component', () => {
      const wrapper = shallowMount(redirectComponent)
    
      Object.defineProperty(window, 'location', {
        value: {
          href: 'http://localhost',
        },
        configurable: true,
      });
    
      it('Redirect By Click Test', () => {
        wrapper.find('.target').trigger('click');
        expect(window.location.href).toEqual('/home');
      })
    })
    

    【讨论】:

      猜你喜欢
      • 2018-10-09
      • 1970-01-01
      • 2014-11-25
      • 2019-02-22
      • 1970-01-01
      • 2018-12-16
      • 2020-08-04
      • 2023-01-13
      • 2019-05-08
      相关资源
      最近更新 更多