首页 > 移动平台 > 详细

[React] Test friendly approach

时间:2017-01-31 21:45:27      阅读:213      评论:0      收藏:0      [点我收藏+]

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.

[React] Test friendly approach

原文:http://www.cnblogs.com/Answer1215/p/6359101.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!