what to test
Do not test the library !
Do not test complex connections !
Do test isolated units
Do test your conditional outpus
Test component
对navigationitems进行测试
import React from 'react';
import { configure , shallow} from 'enzyme';
//shallow只render当前内容,补进行深度render
import Adapter from 'enzyme-adapter-react-16';
import NavigationItems from './NavigationItems';
import NavigationItem from './NavigationItem/NavigationItem';
configure({adapter: new Adapter()});
describe('<NavigationItems />', ()=>{
it('should render two <NavigationItem /> elements if not authenticated', ()=>{
const wrapper = shallow(<NavigationItems/>);
expect(wrapper.find(NavigationItem)).toHaveLength(2);
});
});
//enzyme 只render要测试的component
测试——wrapper——shallow——wrapper.setProps()
import React from 'react';
import { configure , shallow} from 'enzyme';
//shallow只render当前内容,补进行深度render
import Adapter from 'enzyme-adapter-react-16';
import NavigationItems from './NavigationItems';
import NavigationItem from './NavigationItem/NavigationItem';
configure({adapter: new Adapter()});
describe('<NavigationItems />', ()=>{
let wrapper;
beforeEach(()=>{
wrapper = shallow(<NavigationItems/>);
});
//afterEach
it('should render two <NavigationItem /> elements if not authenticated', ()=>{
expect(wrapper.find(NavigationItem)).toHaveLength(2);
});
it('should render three <NavigationItem /> elements if authenticated', ()=>{
// wrapper = shallow(<NavigationItems isAuthenticated/>);
wrapper.setProps({isAuthenticated:true});
expect(wrapper.find(NavigationItem)).toHaveLength(3);
});
});
//enzyme 只render要测试的component
Jest官网
https://jestjs.io/docs/en/getting-started.html
Test container
import {BurgerBuilder} from './BurgerBuilder';
import React from 'react';
import { configure , shallow} from 'enzyme';
//shallow只render当前内容,补进行深度render
import Adapter from 'enzyme-adapter-react-16';
import BuildControls from '../../components/Burger/BuildControls/BuildControls';
configure({adapter: new Adapter()});
describe('<BurgerBuilder />',()=>{
let wrapper;
beforeEach(()=>{
wrapper = shallow(<BurgerBuilder onInitIngredients={()=>{}}/>);
});
it('should render <BuildControls /> when receiving ingredients', ()=>{
wrapper.setProps({ings:{salad:0}});
expect(wrapper.find(BuildControls)).toHaveLength(1);
});
});
Test reducer
import reducer from './auth';
import * as actionTypes from '../actions/actionsTypes';
describe('auth reducer', ()=>{
it('should return the initial state',()=>{
expect(reducer(undefined, {})).toEqual({
token:null,
userId:null,
error:null,
loading:false,
authRedirectPath: '/'
});
});
it('should return the token upon login',()=>{
expect(reducer({
token:null,
userId:null,
error:null,
loading:false,
authRedirectPath: '/'
}, {
type:actionTypes.AUTH_SUCCESS,
idToken:'some-Token',
userId:'some-user-id'
})).toEqual({
token:'some-Token',
userId:'some-user-id',
error:null,
loading:false,
authRedirectPath: '/'
});
});
});