【发布时间】:2021-08-12 15:09:44
【问题描述】:
我需要为在一个函数中被调用两次的函数编写一个测试用例。
async getAssets ( skuId, commonSku) {
const { items } = await this.getMediaSet( skuId );
const { items: commonSkuItems } = commonSku ? await this.getMediaSet( commonSku ) : { items: []};
return [ ...items, ...commonSkuItems ];
}
getMediaSet 方法返回的是一个特定于 skuId 的数据对象,如下所示
const response = {
"items": [
{
"type": "img",
"src": "https://media/25131",
"width": 2000,
"height": 2000,
"format": "PNG",
"opaque": "false"
},
{
"type": "img",
"src": "https://media/23232",
"width": 2000,
"height": 2000,
"format": "PNG",
"opaque": "false"
}
]
}
我尝试测试的方式如下所示
const result = {
"items": [
{
"type": "img",
"src": "https://media/25131",
"width": 2000,
"height": 2000,
"format": "PNG",
"opaque": "false"
},
{
"type": "img",
"src": "https://media/23232",
"width": 2000,
"height": 2000,
"format": "PNG",
"opaque": "false"
}
]
}
const getMediaSet = jest.fn().mockImplementation( () => Promise.resolve( {response} ) );
let output = await getAssets( '251', '253' );
expect( output ).toMatchObject( result );
问题是如何模拟 getMediaSet twice ? 因为我的另一个调用未定义。
【问题讨论】: