开玩笑:如何模拟动画循环?

Jest: How can I mock out Animated loops?

我正在尝试 运行 具有以下动画代码(在 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();
}

我尝试用以下方法模拟 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(),
        };
      }),
    };
  });

但是,运行ning测试结果出现这个错误:

TypeError: animation.reset is not a function

  54 |         iterations: this.props.totalNumPulses
  55 |       }
> 56 |     ).start();
  57 |   }
  58 | 

我已经在各个地方放置了 reset mocking,并检查了 React Native 中 'loop' 方法的源代码,但没有成功地 mock 出来。以前有人成功做过吗?

如果您使用的是 jest,您可以在 __mocks__ 文件夹中为 react-native 创建一个模拟,并从您需要的 React Native 中模拟特定的 function/method 并保留其余的 React -原汁原味。

import * as RN from 'react-native';

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

module.exports = RN;

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

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

// Tests/__mocks__/react-native.js

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

这让我可以跳过动画并更好地测试我的 start 回调。您可以对 Animated!

的任何 属性 或子 属性 使用类似的方法
import { Animated } from 'react-native';

const mockAnimated = () => {
  const mock = jest.fn(() => ({
    delay: () => jest.fn(),
    interpolate: () => jest.fn(),
    timing: () => jest.fn(),
    start: () => jest.fn(),
    stop: () => jest.fn(),
    reset: () => jest.fn(),
  }));

  Animated.parallel = mock;
  Animated.loop = mock;
  ...

  return Animated;
};