這是我寫在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