• 测试简单的 Action

    测试简单的 Action

    考虑下面的简单动作,取自本书的Redux章节:

    1. import { Injectable } from '@angular/core';
    2. import { NgRedux } from 'ng2-redux';
    3. export const INCREMENT_COUNTER = 'INCREMENT_COUNTER';
    4. export const DECREMENT_COUNTER = 'DECREMENT_COUNTER';
    5. @Injectable
    6. export class CounterActions {
    7. constructor(private redux: NgRedux<any>) {}
    8. increment() {
    9. this.redux.dispatch({ type: INCREMENT_COUNTER });
    10. }
    11. decrement() {
    12. this.redux.dispatch({ type: DECREMENT_COUNTER });
    13. }
    14. }

    这些是很简单的测试:

    1. import { NgRedux } from 'ng2-redux';
    2. import {
    3. CounterActions,
    4. INCREMENT_COUNTER,
    5. DECREMENT_COUNTER,
    6. } from './counter';
    7. // Mock out the NgRedux class with just enough to test what we want.
    8. class MockRedux extends NgRedux<any> {
    9. constructor() {
    10. super(null);
    11. }
    12. dispatch = () => undefined;
    13. }
    14. describe('counter action creators', () => {
    15. let actions: CounterActions;
    16. let mockRedux: NgRedux<any>;
    17. beforeEach(() => {
    18. // Initialize mock NgRedux and create a new instance of the
    19. // ActionCreatorService to be tested.
    20. mockRedux = new MockRedux();
    21. actions = new CounterActions(mockRedux);
    22. });
    23. it('increment should dispatch INCREMENT_COUNTER action', () => {
    24. const expectedAction = {
    25. type: INCREMENT_COUNTER
    26. };
    27. spyOn(mockRedux, 'dispatch');
    28. actions.increment();
    29. expect(mockRedux.dispatch).toHaveBeenCalled();
    30. expect(mockRedux.dispatch).toHaveBeenCalledWith(expectedAction);
    31. });
    32. it('decrement should dispatch DECREMENT_COUNTER action', () => {
    33. const expectedAction = {
    34. type: DECREMENT_COUNTER
    35. };
    36. spyOn(mockRedux, 'dispatch');
    37. actions.decrement();
    38. expect(mockRedux.dispatch).toHaveBeenCalled();
    39. expect(mockRedux.dispatch).toHaveBeenCalledWith(expectedAction);
    40. });
    41. });

    我们只是确保我们的action创建者正确地分派actions。