被称为原始函数,而不是被嘲笑的间谍函数

问题描述 投票:0回答:1

我放弃了我认为简单的东西。我有以下承诺:

information.js

// other methods

export async function information() {

  let info= {
    code: ''
  };
  await AsyncStorage.multiGet([
    'code'
  ])
    .then((response) => {
      info['code'] = response[0][1]

    })
    .catch((e) => {
      console.log(e);
    });
  return info;
}

process.js:

从“ ../信息”导入{信息}

Promise.all([information()]).then(function (values) {

  if (values[0]['code'] != null) {
    // tag the code
  }
}).catch(err=>{
  console.log(err)
});

现在在processor.test.js中

import * as info from '../information';

it("should tag service code", async () =>{

  const spy = jest.spyOn(info,"information")
  spy.mockResolvedValue({'code':'ABC'})
  expect(tagCode()).toEqual('ABC_Y')

});

无法说出预期的'ABC_Y',但为空。从已解决的Promise的console.log中,我可以看到它正在执行原始的信息方法,而不是我的间谍,因此始终返回null。

jest
1个回答
0
投票

如果我走错了路,请纠正我,但是可以通过稍微改变测试用例来解决吗?

jest.spyOne(info, 'information').mockImplementationOnce(jest.fn(async () => { code: 'ABC' });

expect(tagCode()).toEqual('ABC_Y');

我还没有测试此代码,只是我在凌晨4:42的意见。

[我选择在我的ockImplementation调用中包括一个jest.fn调用,这使我能够测试其他信息,例如被调用的information():

expect(info.information).toHaveBeenCalledTimes(1);
expect(info.information).toHaveBeenCalledWith({ code: 'ABC' })

希望这至少可以帮助您解决问题,尽管我承认我在Jest方面遇到了很多问题(尤其是依赖关系,尽管这些通常是我因上下文问题所犯的错误)。

我已经读过几次您的问题,但我仍然不能说服我真正理解它,因此,如果以上对您没有用,请接受我的歉意。


export async function information() {

  let info= {
    code: ''
  };
  await AsyncStorage.multiGet([
    'code'
  ])
    .then((response) => {
      // this may produce different results
      info['code'] = response[0][1]

    })
    .catch((e) => {
      console.log(e);
    });
  return info;
}

一个问题可能在上面,您返回的是info,据我所知,它可能包含您的.then语句中的已解析值,据我所知,这不适用于现实。

.then在方法的末尾(在return之后进行处理,因此您的info可能包含空的code,然后过了一段时间就会完成Promise。

我将从上方将其更改为:


export async function information() {

  let info= {
    code: ''
  };
  await AsyncStorage.multiGet([
    'code'
  ])
    .then((response) => {
      info['code'] = response[0][1]
      Promise.resolve(info);
    })
    .catch((e) => {
      console.log(e);
    });
}

尽管我建议不要将Promise与async / await混合使用,因为这是一种很好的射击方式(我当然认为)。

您当然可以通过在return上方和.then内插入注释来测试这一理论,简单的console.log('called') | console.log('called1')会提示您首先调用哪个。

© www.soinside.com 2019 - 2024. All rights reserved.