|
| 1 | +import { Action, Reducer, applyMiddleware, combineReducers, createAction, createStore } from './redux'; |
| 2 | + |
| 3 | +// Dummy Reducer |
| 4 | +const counterReducer: Reducer<number, Action<string>> = (state = 0, action) => { |
| 5 | + switch (action.type) { |
| 6 | + case 'INCREMENT': |
| 7 | + return state + 1; |
| 8 | + case 'DECREMENT': |
| 9 | + return state - 1; |
| 10 | + default: |
| 11 | + return state; |
| 12 | + } |
| 13 | +}; |
| 14 | + |
| 15 | +// Dummy Middleware |
| 16 | +const loggingMiddleware = (storeApi) => (next) => (action) => { |
| 17 | + console.log('Middleware:', action); |
| 18 | + return next(action); |
| 19 | +}; |
| 20 | + |
| 21 | +// Dummy Action Creators |
| 22 | +const increment = createAction('INCREMENT'); |
| 23 | +const decrement = createAction('DECREMENT'); |
| 24 | + |
| 25 | +describe('Redux implementation tests', () => { |
| 26 | + test('createStore works', () => { |
| 27 | + const store = createStore(counterReducer); |
| 28 | + expect(store.getState()).toBe(0); |
| 29 | + }); |
| 30 | + |
| 31 | + test('createStore with applyMiddleware works', () => { |
| 32 | + const store = createStore( |
| 33 | + counterReducer, |
| 34 | + applyMiddleware(loggingMiddleware) |
| 35 | + ); |
| 36 | + expect(store.getState()).toBe(0); |
| 37 | + }); |
| 38 | + |
| 39 | + test('dispatch works', () => { |
| 40 | + const store = createStore(counterReducer); |
| 41 | + store.dispatch(increment()); |
| 42 | + expect(store.getState()).toBe(1); |
| 43 | + store.dispatch(decrement()); |
| 44 | + expect(store.getState()).toBe(0); |
| 45 | + }); |
| 46 | + |
| 47 | + test('combineReducers works', () => { |
| 48 | + const rootReducer = combineReducers({ |
| 49 | + counter: counterReducer, |
| 50 | + }); |
| 51 | + const store = createStore(rootReducer); |
| 52 | + expect(store.getState()).toEqual({ counter: 0 }); |
| 53 | + }); |
| 54 | + |
| 55 | + test('createAction works', () => { |
| 56 | + const incrementAction = increment(); |
| 57 | + expect(incrementAction).toEqual({ type: 'INCREMENT' }); |
| 58 | + const decrementAction = decrement(); |
| 59 | + expect(decrementAction).toEqual({ type: 'DECREMENT' }); |
| 60 | + }); |
| 61 | +}); |
0 commit comments