2

When writing a test, if you need to compare a large amount of data, you probably won't list all the objects that need to be compared, but choose to loop directly.

If there is a loop in the test, a problem that is likely to occur is that you may not be able to quickly locate the problem with which element in the loop occurs when the test fails. At this time, the positioning will be more difficult.

A better way is to add try/catch to Jest to handle errors, so that when an error occurs, some auxiliary information can be printed to quickly locate, such as

it('test-error-catch-example',() => {

   let needTestData = [1,2,3,4]

   needTestData.foreach( item => {
       let result = doSomething(item)
       // 这里开始是新增的
       try{
          expect(result).toBe(true)
       }catch(e){
          console.log("error key",item)
          throw e;
       }
       // 新增的错误处理结束
   })

})

By adding a custom try catch, when there is a problem, on the one hand, the Error can be thrown in the normal way, waiting for Jest to process it, on the other hand, the customized information can be output during the catch, which is convenient for us to check and repair.


白宦成
1.3k 声望3.2k 粉丝

西秦公子