Jest: 我该如何模拟动画循环?

8

我正在尝试为一个动画组件运行快照测试,该组件具有以下动画代码(在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();
}

我尝试模拟以下动画:
  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(),
        };
      }),
    };
  });

然而,运行测试会导致这个错误:
TypeError: animation.reset is not a function

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

我已经在不同的位置放置了重置模拟,并检查了React Native中“loop”方法的源代码,但没有成功地模拟出来。有人之前成功地做到了吗?

3个回答

8
你的例子存在问题,你完全将 Animated 替换为一个对象,而不是只替换需要测试的方法。
在下面的示例中,我模拟 parallel().start(callback) 方法,使其立即调用回调函数。
// Tests/__mocks__/react-native.js

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

这使我能够跳过动画,更好地测试我的start回调。您可以使用类似的方法来处理Animated的任何属性或子属性!

6

如果你正在使用jest,你可以在__mocks__文件夹中为react-native创建一个模拟,并模拟你需要的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;

0
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;
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接