【问题标题】:How to mock function which is called twice jest如何模拟两次开玩笑的函数
【发布时间】: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 因为我的另一个调用未定义。

【问题讨论】:

    标签: reactjs jestjs graphql


    【解决方案1】:

    所以,我找到了答案。我们需要像这样更改函数模拟实现

       cmsDataSource.getMediaSet = jest
        .fn()
        .mockReturnValue( response ) // Response in first call
        .mockReturnValueOnce( response ) // Response in second call
    

    代替

     const getMediaSet = jest.fn().mockImplementation( () => Promise.resolve( {response} ) );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-07
      • 2020-10-20
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-18
      相关资源
      最近更新 更多