React test Study

1.simulate可以模拟点击或者状态改变

cashFundCard.find('.btn').simulate('click');
cashFundCard.find('input').simulate('change', {target: {value: '0'}});

2.创建实例,就可以调用组件里面的方法

import { shallow } from 'enzyme';
import RegistryListPanel from ‘.’;

describe('<RegistryListPanel />', () => {
    const shallowCreator = (props) => {
        return shallow(
            <RegistryListPanel coupleRegistries={props} />
        );
    };
    describe('#state', () => {
        it('the state of isOpen is false by default', () => {
            const wrapper = shallowCreator();
            expect(wrapper.state('isOpen')).to.eq(false);
        });
    
        it('the state of isOpen is true when the button be clicked', ()=> {
            const wrapper = shallowCreator();
            const inst = wrapper.instance();
            inst.collapsedClick();
            expect(wrapper.state('isOpen')).to.eq(true);
        });
    });
});


3. Enzyme https://github.com/airbnb/enzyme

Enzyme is a JavaScript Testing utility for React that makes it easier to assert, manipulate, and traverse your react Components' output. (为React的设计的JavaScript测试工具)

1)shallow 函数, 它支持对DOM的进行结构和事件的响应,如果你对jQuery比较熟悉的话,那么你对它的语法也不会陌生。比如我们测试里用到的find方法,大家经常用它来寻找一些DOM数组。

2)mount函数, 完全DOM渲染主要用于与DOM API进行交互以及需要完整生命周期的组件测试(i.e componentDidMoun)。

3)render函数,静态渲染,enzyme还提供了静态渲染,将组件渲染成html,用于我们分析html的结构。render相比前两种用法, 主要是在于更换了类库 Cheerio ,而且作者也相信在处理解析上会更好点。

import { shallow, mount, render } from 'enzyme';
import sinon from 'sinon';
import chai from "chai";
import sinonChai from "sinon-chai";
chai.use(sinonChai);


4. Sinon.js    http://sinonjs.org/

 standalone test spies, stubs, and mocks for JavaScript. Work with any unit testing framework.

(aka, 允许你把代码中难以被测试的部分替换为更容易测试的内容)

Sinon将测试替身分为3种类型:

  • Spies, 可以提供函数调用的信息,但不会改变函数的行为

  • Stubs, 与spies类似,但是会完全替换目标函数。这使得一个被stubbed的函数可以做任何你想要的 —— 例如抛出一个异常,返回某个特定值等等。

  • Mocks, 通过组合spies和stubs,使替换一个完整对象更容易。

1)使用spy,原始的函数依然会被调用。

2)使用stub,原始函数就不会被执行了。stub不需要模拟所有的行为,只需要足够你的测试项使用即可,其它细节可以忽略。

另外一些stub的常用场景是验证一个函数是否使用特定的参数。


5.to.match(/Add a store/) 匹配文字     to.eq('add') 是否相等


6.单独跑某个测试 使用describe.only 和 it.only 


7.Mocha 一款Javascript单元测试框架

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章