这是我写在Mocha/Chai中的一个测试存根。我可以轻松地发出一个动作并声明状态与我期望的相同,但我如何验证它是否遵循了预期的过程(IE早期的测试)?如何单元测试使用还原thunk的还原应用程序
/**
* This test describes the INITIALIZE_STATE action.
* The action is asynchronous using the async/await pattern to query
* The database. The action creator returns a thunk which should in turn
* return the new state with a list of tables and their relationships with eachother
**/
describe('Initialize state',() => {
it('Should check if state is empty',() => {});
it('Should check if tables/relationships exist',() => {});
it('Should check if new tables have been added',() => {});
it('Should merge new and existing tables and relationships',() => {
// Here is where we would dispatch the INITIALIZE_STATE
// action and assert that the new state is what I expect it to be.
});
});
我还没有为实际操作本身编写任何代码,因为我希望代码能够通过这些验证。一些伪代码可能看起来像这样
export function initializeState() {
return function(dispatch) {
let empty = store.getState().empty
let state = (empty) ? await getLastPersistedState() : store.getState()
let tables = state.tables;
let payload = tables.concat(await getNewTables(tables));
dispatch({type: 'INITIALIZE_STATE', payload});
}
}
function getLastPerisistedState() {
return mongodb.findall(state, (s) => s);
}
function getNewTables(tableFilter) {
return sql.query("select table_name from tables where table_name not in (" + tableFilter + ")");
}
你想调用实际的mongo/SQL函数,或者模拟它们吗?我的标准方法是保持异步的东西(这里是thunk),以便不需要测试,并测试它周围的所有东西 - 例如用模拟有效载荷测试'INITIALIZE_STATE'动作。 – nrabinowitz