美文网首页
记一次测试bug的解决过程

记一次测试bug的解决过程

作者: 吴一晏 | 来源:发表于2019-06-15 14:02 被阅读0次
    在写测试用例的时候,发现了一个报错,虽然测试用例都通过了,但是看到有报错还是很难受的 报错信息.jpg

    在目前我的所有代码中,只有在toast.vue里写了style

    setLineHeight() {
          this.$nextTick(() => {
            this.$refs.line.style.height = `${
              this.$refs.toast.getBoundingClientRect().height
            }px`;
          });
        }
    

    而且这个函数只在mounted中执行了一次:

    mounted() {
        this.setLineHeight();
        this.execAutoClose();
      }
    

    于是我在mounted、和setLineHeight中都log了这个style

    mounted() {
        console.log(this.$el.outerHTML)
        this.setLineHeight();
        this.execAutoClose();
      }
    
    setLineHeight() {
          this.$nextTick(() => {
            console.log(this.$refs)
            console.log(this.$refs.line)
            this.$refs.line.style.height = `${
              this.$refs.toast.getBoundingClientRect().height
            }px`;
          });
        }
    

    发现了this.$refs.lineundefined
    因为后两个log是在nextTick中执行的,和第一个log存在一点点的时间间隙

    再看我的测试代码

    it('接受 closeButton',() => {
                const callback = sinon.fake();
                const Constructor = Vue.extend(Toast)
                const vm = new Constructor({
                    propsData: {
                        closeButton: {
                            text: '关闭他',
                            callback,
                        }
                    }
                }).$mount()
                let closeButton = vm.$el.querySelector('.close')
                expect(closeButton.textContent.trim()).to.eq('关闭他')
                closeButton.click()
                expect(callback).to.have.been.called
            })
    

    发现了在mounted 后立马接了一个closeButton.click() ,触发了我写的关闭函数,把标签都摧毁了

    close() {
          this.$el.remove();
          this.$emit("close");
          this.$destroy();
        }
    

    所以经过分析,是click触发关闭函数太快了,所以this.$refs.line的结果是undefined

    因此解决方法就是把click放在一个setTimeout函数里

    setTimeout(() => {
                    closeButton.click()
                    expect(callback).to.have.been.called
                    done() //测试用例异步需要执行一个done
                },200) 
    

    这样就通过了测试用例,而且还没有讨厌的报错,强迫症患者舒服了。

    相关文章

      网友评论

          本文标题:记一次测试bug的解决过程

          本文链接:https://www.haomeiwen.com/subject/bdlbfctx.html