I am trying to test a Redux Action in my App. I am mocking the function that add the item in the redux store because I only want to check if it was stored in the database. However when I run the test the item is not being stored nor the mock function gets called.
I think is something related with async calls since Database.ref.push returns a promise. I wouldn't like to change my Action.js code (because is being used in many places) just to make the test work.
Is there another way to test it?
Action.js
import database from '../firebase/firebase'
export const addExpense = (expenseData = {}) => {
return (dispatch) => {
const {
description = '',
note = '',
amount = 0,
createdAt = 0
} = expenseData;
const expense = {
description,
note,
amount,
createdAt
};
database.ref('expenses').push(expense).then((ref) => {
dispatch({
type: 'ADD_EXPENSE',
expense: {
id: ref.key,
...expense
}
});
});
};
};
Test.js
test('should save expense in Database', () => {
const spy = jest.fn();
const action = addExpense(expenses[0]);
action(spy);
expect(spy).toHaveBeenLastCalledWith({
type: 'ADD_EXPENSE',
expense: expenses[0]
});
});
LOGS
FAIL src\tests\actions\expenses.test.js
● should setup add expense action object with provided values
expect(jest.fn()).toHaveBeenLastCalledWith(expected)
Expected mock function to have been last called with:
[{"expense": {"amount": 195, "createdAt": 0, "description": "Gum", "id": "1", "note": ""}, "type": "ADD_EXPENSE"}]
But it was not called.
at Object.<anonymous> (src/tests/actions/expenses.test.js:37:15)
at Promise (<anonymous>)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:169:7)
Aucun commentaire:
Enregistrer un commentaire