JS unit testing and principle

unit test

Unit testing software refers to the smallest unit to check and validate the test, the test can be detected by means of the potential bug, can quickly output feedback function, whether the expected authentication code, the code can guarantee the security of the reconstructed.

There is such a method:

let add = (a, b) => a + b;

This is a method of two numbers and a very simple calculation, if we want to see his logic right, we can call it, then the next comparison with the value we expected, if it does not throw an error:

let add = (a, b) => a + b;
let result = add(1, 2);
let expect = 3;
if(result !== expect){
  throw new Error(`1+2应该等于${expect},实际等于${result}`)
}

In fact, this is the principle of unit testing, but here write way too straightforward, and can not be reused, let us transform the next expect, turning it into a generic method:

const expect = (res) => {
  return {
    toBe: (expectRes) => {
      if(res !== expectRes){
        throw new Error(`期望值是${expectRes},但实际上却是${res}!`)
      }
    }
  }
}

Our previous expectation 1+2=3, which is actually a unit test cases, when we have multiple use cases, we can use a more elegant way to write generic use cases, we have to write a generic method for example:

const test = (desc, fn) => {
  try{
    fn();
    console.log(`${desc} -> PASS`)
  }catch(e){
    console.error(`${desc} -> FAIL`, e);
  }
}

We use two common methods to rewrite our unit under test:

let add = (a, b) => a + b;

const expect = (res) => {
  return {
    toBe: (expectRes) => {
      if(res !== expectRes){
        throw new Error(`期望值是${expectRes},但实际上却是${res}!`)
      }
    }
  }
}

const test = (desc, fn) => {
  try{
    fn();
    console.log(`${desc} -> PASS`)
  }catch(e){
    console.error(`${desc} -> FAIL`, e);
  }
}

test('1+2=3', () => {
  expect(add(1,2)).toBe(3); // 1+2=3 -> PASS
});

test('1+2=4', () => {
  expect(add(1,2)).toBe(4); // 1+2=4 -> FAIL Error: 期望值是4,但实际上却是3!
});

Described above is the principle of unit testing, in fact, when we write unit tests do not need to write expectand testshare methods, alignment methods need to use far more than toBea. We may use third-party libraries directly Jest , he contains almost all the tools we need to use the official website has, here mainly about the principle, using methods not repeat

Guess you like

Origin www.cnblogs.com/dennisj/p/12175807.html