test_middleware-task-01.js (1743B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 "use strict"; 6 7 const { 8 createStore, 9 applyMiddleware, 10 } = require("resource://devtools/client/shared/vendor/redux.js"); 11 const { 12 task, 13 } = require("resource://devtools/client/shared/redux/middleware/task.js"); 14 15 /** 16 * Tests that task middleware allows dispatching generators, promises and objects 17 * that return actions; 18 */ 19 add_task(async function () { 20 const store = applyMiddleware(task)(createStore)(reducer); 21 22 store.dispatch(fetch1("generator")); 23 await waitUntilState(store, () => store.getState().length === 1); 24 equal( 25 store.getState()[0].data, 26 "generator", 27 "task middleware async dispatches an action via generator" 28 ); 29 30 store.dispatch(fetch2("sync")); 31 await waitUntilState(store, () => store.getState().length === 2); 32 equal( 33 store.getState()[1].data, 34 "sync", 35 "task middleware sync dispatches an action via sync" 36 ); 37 }); 38 39 function fetch1(data) { 40 return async function ({ dispatch, getState }) { 41 equal( 42 getState().length, 43 0, 44 "`getState` is accessible in a generator action" 45 ); 46 let moreData = await new Promise(resolve => resolve(data)); 47 // Ensure it handles more than one yield 48 moreData = await new Promise(resolve => resolve(data)); 49 dispatch({ type: "fetch1", data: moreData }); 50 }; 51 } 52 53 function fetch2(data) { 54 return { 55 type: "fetch2", 56 data, 57 }; 58 } 59 60 function reducer(state = [], action) { 61 info("Action called: " + action.type); 62 if (["fetch1", "fetch2"].includes(action.type)) { 63 state.push(action); 64 } 65 return [...state]; 66 }