【问题标题】:How to mock AsyncStorage in jest?如何开玩笑地模拟 AsyncStorage?
【发布时间】:2018-06-06 05:48:34
【问题描述】:

我正在使用 jest 对 react-native 应用程序进行单元测试。我在我的一个组件中使用了 AsyncStorage。

componentWillMount() {
    this.setState({ avatarSource: null });
    AsyncStorage.getItem('UserDetails', (err, result) => {
      var objData = JSON.parse(result);
      this.setState({ userdetail: objData });
      axios.get(SERVER_URL + '/image/' + objData.userId + '.jpg' + '?$' + Math.random())
          .then(response => {
              var obj = { uri: response.config.url };
              this.setState({ avatarSource: obj });
      });
    });
}

如何在我的测试文件中模拟来自 AsyncStorage 的“结果”?

【问题讨论】:

标签: unit-testing react-native jestjs enzyme asyncstorage


【解决方案1】:

测试get方法的最好方法是:

describe('Verifying getData function returns the right value', () => {
    it('Function getData must return the correct value given date', async function () {
        await getData('SOME_KEY');
        expect(AsyncStorage.getItem).toBeCalledWith('SOME_KEY');
    });
});

【讨论】:

    猜你喜欢
    • 2020-11-18
    • 2017-07-01
    • 1970-01-01
    • 2020-08-20
    • 2021-05-27
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多