"仿京东"h5端遇到的小坑

1,048 阅读2分钟

需求说明:

当订单商品数量小于或者等于2时,展示所有商品;当数量大于2的时候,只展示两个商品,通过按钮控制来展示所有商品

不够合理的测试

firstTest.gif 由于本人手动验收测试的时候,不够仔细;写完代码以为成功实现后;并没有发现比较系统化的测试过,产生了bug。如上图所示,咋看之下没有任何的问题。

发现bug

discoverTheBug.gif 在后面的开发过程中,验收整个模块的时候,发现了这个问题。

代码

//html展示代码
<template v-for="(item, index) in productList" :key="item._id">
<div class="products_item" v-if="index <= isShowProducts">
//功能实现代码
const useOrderExpandEffect = (orderProducts) => {  
const isShowProducts = ref(2)  
const handleExpand = () => {   if (isShowProducts.value !== orderProducts) {      
isShowProducts.value = orderProducts    
} else {      isShowProducts.value = 2        }   
}  return {    handleExpand,    isShowProducts  }
}
//setup()调用代码
const orderProducts = Object.keys(productList.value).lengthconst {  handleExpand,  isShowProducts} = useOrderExpandEffect(orderProducts)

定位问题

看到部分商品展示不正确的时候,我又检查了一遍代码逻辑;发现逻辑上没有问题之后,我便去检查一下productList这个数据在渲染的时候,是否正确获取到了。于是把productList打印出来了。

productList.png 发现productList里面的value的key值是3,4;是一个Object;我的代码展示数据部分是循环index in productList,于是我认为这个index获取得到是key值,而不是我想要的索引值,我便去查找Vue的文档关于v-for with an object关于v-for有三个参数。 example:

<li v-for="(value, key, index) in myObject">
{{ index }}. {{ key }}: {{ value }}
</li>

解决方案

由于我个人不喜欢代码有定义的参数没有使用,于是我决定把productList从object转化成array类型来满足我的需求。于是修改为:

代码

const useOrderExpandEffect = (productList) => {  
// 将productList的数据类型转化为数组,以保证获取index按照顺序排列  
const productListArr = Object.values(productList.value) 
const orderProducts = productListArr.length 
const isShowProducts = ref(1)  
const handleExpand = () => {    
if (isShowProducts.value !== orderProducts) {      
isShowProducts.value = orderProducts    } 
else {      isShowProducts.value = 1    } } 
const totalNum = computed(() => {    
let total = 0    
for (const i of productListArr) {      
total += i.count    }    
return total }) 
return {    handleExpand,    isShowProducts,    productListArr,    
totalNum  }}

实现效果

fixBug.gif

总结

造成这个bug没有及时发现以及发生的原因是:

  • 对于功能测试方案设计不够仔细
  • v-for的实现不够理解透彻

改进: 对于功能测试需要设计更加好的测试方案,学习思考一个代码封装下的具体实现过程;才能更好的了解其运行机制。

项目地址:github.com/AlexL0ng/im…