【问题标题】:Using jest for unit test in vuejs + laravel在 vuejs + laravel 中使用 jest 进行单元测试
【发布时间】:2018-03-04 15:57:20
【问题描述】:

在我的 vue js 组件中,我有这个

<template>
    <div class="timing_fund_redirect">Your fund will drop in {{ timer }} seconds.</div>
</template>

如何在 Jest 中对该部分进行单元测试

假设我有

methods: {
            fundTimer() {
                var countdown = 10;

                window.setInterval(function() {
                    (countdown < 1) ? window.location = _this.path : _this.timer = countdown;
                    countdown--;
                },1000);
            }
        }

【问题讨论】:

    标签: unit-testing vue.js jestjs


    【解决方案1】:

    一般来说,如果你想使用 Jest 测试基于时间的 javascript,你可以使用timer mocks。如果您想测试您是否正确设置了“计时器”数据属性,那么测试起来相对容易:

    import Timer from './Timer.vue'
    import Vue from 'vue'
    
    jest.useFakeTimers();
    
    describe('it works', () => {
       it('sets the timer property correctly', () => {
          jest.runTimersToTime(3000);
          // remember to call this in a nextTick callback so your component has a change to update properly
          Vue.nextTick(() => {
            // you don't do your first reduction of the property until one second is elapsed, so after 3 seconds, timer will equal 8
            expect(Timer.data().timer).toBe(8) 
          }) 
       }
    });
    

    至于测试您的重定向是否有效,您可以使用runTimersToTime 将计时器运行到超过 10 秒阈值的数字。模拟 window.location 对象本身有点棘手,但我通常喜欢将 URL 重定向抽象到一个单独的模块中,所以你可以这样做,然后监视你的重定向方法以确保它被调用。

    我假设您使用的是_this,因此您可以在您的setTimeout 回调范围内访问您的Vue 组件,尽管我看不到您在哪里设置它。 您可以只使用箭头函数来允许您在该回调中访问组件的数据属性。

    另外,你并不需要本地的countdown变量,你可以直接修改timer属性。

    data () {
      return {
        timer: 10
      }
    },
    methods: {
      fundTimer() {
         window.setInterval(() => {
            (this.timer < 1) ? window.location = this.path : this.timer--;
         },1000);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-16
      • 2020-12-17
      • 2020-05-15
      • 2018-09-30
      • 1970-01-01
      • 2019-10-26
      • 2020-12-30
      • 2020-11-12
      • 2020-12-28
      相关资源
      最近更新 更多