Jest玩Redux动作

时间:2017-10-06 09:07:44

标签: javascript reactjs unit-testing redux jestjs

我正在尝试使用snapshots实施jest,但我遇到了问题。解决方案可能很简单,但我找不到它。

LoginForm.js

class LoginForm extends React.Component {
    constructor(props) {
        super(props)
        }
    }
    componentWillMount(){
        this.props.startSpinner()
    }
    render(){
        return(....)
    }
}

LoginForm.spec.js

it('should render snapshot', () => {
    const component = renderer.create(
            <LoginForm />
    )
    const tree = component.toJSON()
    expect(tree).toMatchSnapshot()
})

startSpinner 操作

export function startSpinner() {
    return (dispatch) => {
        dispatch({
            type: 'WINDOW_START_SPINNER',
        })
    }
}

当我运行测试时,它会抛出此错误,不仅是这个操作,还有所有被称为redux操作的函数。

  

TypeError:this.props.startSpinner不是函数

如何使jestredux行动感到满意?

3 个答案:

答案 0 :(得分:2)

您忘记在单元测试中传递override var intrinsicContentSize: CGSize { return UILayoutFittingExpandedSize } 作为道具。如果你只需要测试渲染函数,你应该传递类似constructor(private router: Router, private actorService: ActorService, private route: ActivatedRoute, private location: Location) {} ngOnInit(): void { this.route.params .mergeMap( (params: Params) => { if(params['name']) { return this.actorService.getActor(param['name']); } return Observable.of(false); } ) .subscribe((actor: any) => { if (actor ) { this.actor = actor; }else { this.router.navigate(['/actors']); } }); } 函数的东西(lodash提供一个)。

      <ion-item *ngIf="selectedCities">
              <ion-label floating>Cities</ion-label>
              <ion-icon name="ios-navigate" item-left></ion-icon>
              <ion-select  formControlName="city" [(ngModel)]="sCity">
                <ion-option [value]="sCity" *ngFor="let sCity of 
selectedCities">{{sCity.name}}</ion-option>
              </ion-select>
            </ion-item>

对于redux动作,我会单独测试它们(jest快照也很适合它们)。

答案 1 :(得分:2)

我会单独测试redux功能,并将startSpinner作为模拟函数传递。

e.g:

const mockFn = jest.fn()
const component = renderer.create(
   <LoginForm startSpinner={mockFn} />
)
expect(mockFn.toHaveBeenCalled()).toBe(true)

答案 2 :(得分:1)

我相信你没有正确地应用测试。您必须单独测试操作,缩减器和组件,

测试失败,因为LoginForm组件正在尝试使用connect函数而未被提供程序包装,因此它正在尝试访问一个不常见的商店。

要在测试中实现snapsots,你应该首先模拟一个商店,那里有一个很好的模拟器,你可以在这里找到它: https://github.com/arnaudbenard/redux-mock-store

然后,您必须配置您的商店,在我的项目中我做这样的事情,随意改变它:

// Import your actions and their names (I separate the names in a 
// different file to avoid typos.
import * as actions from '../../src/actions';
import * as types from '../../src/actions';

// You must import an Initial state or create one, I usually import
// the one I have in the reducer.
import { INITIAL_STATE } from '../../src/reducers/AuthReducer'
// Import your middleware and redux mock store
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import MockAdapter from 'axios-mock-adapter';

// --- Mocking config --> Crete your store
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
let store = mockStore(INITIAL_STATE);

// Clear actions before each time
beforeEach(() => {
  store.clearActions();
});

现在只测试你的行动:

describe('[ ScannerActions ]', () => {
  describe('*** toggleCamera()', () => {
    it('Should dispatch TOGGLE_CAMERA action', () => {
      store.dispatch(actions.toggleCamera());
      expect(store.getActions()).toMatchSnapshot();
    })
  });
});