I have defined an action in my mobx store like this:
// CardsStore.js
import FetchData from './FetchData';
export default class CardsStore {
@observable cards = [];
@action fetchCards = async () => {
try {
this.cards = await FetchData();
} catch (error) {
// handling error
}
};
...
other actions and computed values
...
}
and this is the implementation for FetchData:
import EndpointService from 'app/services/EndpointService';
const endpointService = new EndpointService();
export default async function fetchData() {
try {
return await endpointService.getCards();
} catch (e) {
return 'caught';
}
}
I have created a mock module for FetchData
inside __ mocks __ folder that instead of calling the endpoint service returns a hard coded array like this:
// ./__mocks__/FetchData.js
const cards = [
{
id: 'some-id-1',
name: 'Test1',
},
{
id: 'some-id-2',
name: 'Test2',
},
];
export default function FetchData() {
return new Promise((resolve, reject) => {
process.nextTick(() =>
cards ? resolve(cards) : reject({ error: 'Cards are not found.' })
);
});
}
In my cards.test.js file I test it like this and it works:
import CardsStore from './CardsStore.js';
jest.mock('./FetchData');
const cards = [
{
id: 'some-id-1',
name: 'Test1',
},
{
id: 'some-id-2',
name: 'Test2',
},
];
describe('when fetch cards is called', () => {
const cardsStore = new CardsStore();
it('should load the cards', async () => {
await cardsStore.fetchCards();
expect(cardsStore.cards).toEqual(cards);
});
});
The problem is if I want to test my other action addNewCard
then I need to dynamically change the cards and add a new card and then check to see if the expected cards list is equal to the new one (that should contain 3 cards)
I can't find a way to dynamically update the cards array inside ./__mocks__/FetchData.js