zoukankan      html  css  js  c++  java
  • [React] Test friendly approach

    Add functional function such as change state, this should have tests covered.

    For example, in a component, there is a function call 'addBox':

        onAddBox = () => {
            const newBox = {
                id    : this.state.boxes.length,
                color : 'red'
            };
    
            const boxes = addBox(this.state.boxes, newBox);
    
            this.setState({ boxes });
        };

    Here we use a function call 'addBox', this is written in a new file:

    export const addBox = (boxes, newBox) => boxes.concat(newBox);

    SO when need to use it, we need to import it to the component, not just write this function into component methods. Because if we make this function sprated from component methods, we are able to test it by just simply import this function to the test file.

    import {addBox} from '../components/App/AppHelper';
    
    const boxes = [
        {
            id    : 0,
            color : 'red'
        },
        {
            id    : 1,
            color : 'red'
        }
    ];
    
    const newBox = {
        id: 2,
        color: 'green'
    };
    
    test('Should be able to add new box', () => {
       const expected = [
           {
               id    : 0,
               color : 'red'
           },
           {
               id    : 1,
               color : 'red'
           },
           {
               id: 2,
               color: 'green'
           }
       ];
       const result = addBox(boxes, newBox);
       expect(result).toEqual(expected);
    });
    
    test('addBox should be immutable', () => {
        const result = addBox(boxes, newBox);
        expect(result).not.toBe(boxes);
    });

    Here has two test, one is to test 'addBox' should actually add a new box to the existing array. Second test is to make sure we don't mutatue origianl data.

  • 相关阅读:
    题解 P2810 【Catch the theives】
    2020.11.27 考试题解
    2020.11.25 考试题解
    题解 SP16254 【RMID2
    2020.11.24 考试题解
    2020.11.23 考试题解
    CSP-2020 T3 函数调用
    二维树状数组学习笔记
    题解 P4910 【帕秋莉的手环】
    Python实现向指定IP的目标机器拷贝文件
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6359101.html
Copyright © 2011-2022 走看看