我在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
内的纸牌阵列的方法
答案 0 :(得分:0)
使用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);
});
});