我在mobx商店中定义了一个动作,如下所示:
// 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
...
}
这是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';
}
}
我在__mocks __文件夹中为
FetchData
创建了一个模拟模块,而不是调用终结点服务返回了这样的硬编码数组:// ./__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.' })
);
});
}
在我的cards.test.js文件中,我对此进行了测试,并且可以正常工作:
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);
});
});
问题是,如果我想测试其他动作
addNewCard
,则需要动态更改卡并添加新卡,然后检查预期的卡列表是否等于新卡(应包含3张卡)我找不到动态更新
./__mocks__/FetchData.js
中的cards数组的方法 最佳答案
使用jest.spyOn和mockReturnValue ...
jest.spyOn(cardsStore.prototype, "fetchCards").mockReturnValue(Promise.resolve(obj));
将obj替换为您要返回的任何内容
例,
describe('when fetch cards is called', () => {
const cardsStore = new CardsStore();
it('should load the cards', async () => {
jest.spyOn(cardsStore.prototype, "fetchCards").mockReturnValue(Promise.resolve(obj));
await cardsStore.fetchCards();
expect(cardsStore.cards).toEqual(cards);
});
});