我目前正在尝试为我的React Native应用程序编写Jest测试,像这样测试我的提取命令:
const token = await AsyncStorage.getItem("id");
let response = await fetch('http://192.168.0.12:3000/auth/login', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}
});
let res = await response.json();
...rest of code
但是我似乎找不到以前版本的Async Storage的任何模拟解决方案(即 WITHIN React Native,而不是当前的@ react-native-community / async-storage 。目前,我已经尝试过像这样完全模拟模块,并检查是否曾经调用过getItem()方法:
test('tests Login', () => {
jest.mock('react-native', () => {
AsyncStorage: {
getItem: jest.fn(() => {
return new Promise((resolve, reject)=>{
resolve("cool");
});
})
}
});
expect(AsyncStorage.getItem).toBeCalled();
});
但这当前会返回以下错误:
expect(jest.fn()).toBeCalled()
Expected number of calls: >= 1
Received number of calls: 0
当我将其更改为此(我认为这不是正确的方法):
expect(AsyncStorage.getItem()).toBeCalled()
它返回无法解决的承诺:
expect(received).toBeCalled()
Received has type: object
Received has value: {"_40": 0, "_55":undefined, "_65": 1, "_72": null}
我的问题是,如何模拟旧版本的AsyncStorage来检查该函数是否已被调用,或使模拟返回常量值,以便测试可以执行其余方法 ?任何帮助,将不胜感激。我尝试了在SO上建议的各种解决方案,但所有解决方案都返回了相同的错误。我正在使用的当前软件是: React Native(Expo SDK 37.0.0), 笑话, 反应测试渲染器