代码之家  ›  专栏  ›  技术社区  ›  johnny

笑话:我如何模仿动画循环?

  •  4
  • johnny  · 技术社区  · 7 年前

    我正在尝试对动画组件运行快照测试,该组件具有以下动画代码(在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”方法的源代码,但是没有成功模拟它。以前有人成功过吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Brendan McGill    6 年前

    你的例子中的问题是你完全取代了 Animated 使用对象,而不仅仅是替换需要测试的方法。

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

    jest.mock('Animated', () => ({
      ...jest.requireActual('Animated'),
      parallel: () => ({
        start: (callback) => callback()
      })
    }));
    

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

    您可以在测试的顶部执行此操作,甚至在使用 doMock

        2
  •  1
  •   Renan Borges    7 年前

    如果使用的是笑话,则可以为 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;