笑话:如何模拟动画循环?

wil*_*lc0 6 jestjs react-native react-animated

我正在尝试为具有以下动画代码(在componentDidMount上调用)的动画组件运行快照测试:

animate() {
  Animated.loop(
    Animated.sequence([
      Animated.timing(this.state.pulseAnimation, {
        toValue: 1,
        duration: 1000,
        easing: Easing.in(Easing.ease)
      })
    ]),
    {
      iterations: this.props.totalNumPulses
    }
  ).start();
}
Run Code Online (Sandbox Code Playgroud)

我尝试用以下方法模拟Animated:

  jest.mock('Animated', () => {
    return {
      loop: jest.fn(() => {
        return {
          start: jest.fn(),
          reset: jest.fn()
        };
      }),
      timing: jest.fn(() => {
        return {
          start: jest.fn(),
        };
      }),
      Value: jest.fn(() => {
        return {
          interpolate: jest.fn(),
        };
      }),
    };
  });
Run Code Online (Sandbox Code Playgroud)

但是,运行测试会导致以下错误:

TypeError: animation.reset is not a function

  54 |         iterations: this.props.totalNumPulses
  55 |       }
> 56 |     ).start();
  57 |   }
  58 | 
Run Code Online (Sandbox Code Playgroud)

我已经将重设模拟放置在不同的地方,并检查了React Native中“ loop”方法的源代码,但是还没有运气成功地模拟了它。以前有人成功做到过吗?

Ren*_*ges 6

如果您使用 jest,您可以在文件夹react-native内 创建一个模拟__mocks__,并模拟您需要的 React Native 的特定函数/方法,并保持 React-Native 的其余部分不变。

import * as RN from 'react-native';

RN.Animated.timing = () => ({ // I'm mocking the Animated.timing here
    start: () => jest.fn(),
});

module.exports = RN;
Run Code Online (Sandbox Code Playgroud)


Bre*_*ill 6

您示例中的问题是您正在完全替换Animated为一个对象,而不仅仅是替换您需要测试的方法。

在下面的示例中,我进行了模拟,parallel().start(callback)以便它立即调用回调。

// Tests/__mocks__/react-native.js

export const Animated = {
  ...RN.Animated,
  parallel: () => ({
    // immediately invoke callback
    start: (cb: () => void) => cb()
  })
};
Run Code Online (Sandbox Code Playgroud)

这让我可以跳过动画并更好地测试我的start回调。您可以对Animated! 的任何属性或子属性使用类似的方法。