与嵌套反应-导航组件玩笑快照测试 - 对象键改变,因此快照匹配失败(Snapshot test wi

2019-09-25 16:41发布

当我在我的StackNavigator.test.js运行我开玩笑测试总是失败,因为生成密钥

- Snapshot
+ Received

@@ -79,11 +79,11 @@
              fromRoute={null}
              index={0}
              navigation={
                Object {
                  "_childrenNavigation": Object {
-                   "**id-1542980055400-0**": Object {
+                   "**id-1542980068677-0**": Object {
                      "actions": Object {
                        "dismiss": [Function],
                        "goBack": [Function],
                        "navigate": [Function],
                        "pop": [Function],
@@ -109,11 +109,11 @@
                      "replace": [Function],
                      "reset": [Function],
                      "router": undefined,
                      "setParams": [Function],
                      "state": Object {
-                       "key": "**id-1542980055400-0**",
+                       "key": "**id-1542980068677-0**",
                        "routeName": "SignInOrRegister",
                      },
                    },
                  },
                  "actions": Object {
@@ -157,15 +157,15 @@
                  },
                  "setParams": [Function],
                  "state": Object {
                    "index": 0,
                    "isTransitioning": false,
-                   "key": "**id-1542980055400-1**",
+                   "key": "**id-1542980068677-1**",
                    "routeName": "FluidTransitionNavigator",
                    "routes": Array [
                      Object {
-                       "key": "**id-1542980055400-0**",
+                       "key": "**id-1542980068677-0**",
                        "routeName": "SignInOrRegister",
                      },
                    ],
                  },
                }
@@ -191,11 +191,11 @@
                    "overflow": "hidden",
                  },
                  undefined,
                ]
              }
-             toRoute="**id-1542980055400-0**"
+             toRoute="**id-1542980068677-0**"
            >
              <View
                style={
                  Object {
                    "bottom": 0,

所述StackNavigator组件使用“反应导航”和具有从“反应导航流体跃迁”的嵌套FluidTransition组分:

StackNavigator.js

import React, { Component } from 'react';
import { Platform, Animated, Easing } from 'react-native';
import { createStackNavigator } from 'react-navigation';
import { ThemeContext, getTheme } from 'react-native-material-ui';
import PropTypes from 'prop-types'

import FluidTransitionNavigator from './FluidTransitionNavigator';
import Dashboard from './../pages/Dashboard';
import Login from './../pages/Login';
import SignInOrRegister from './../pages/SignInOrRegister';

import UniToolbar from './UniToolbar';

const transitionConfig = () => {
  return {
    transitionSpec: {
      duration: 1000,
      easing: Easing.out(Easing.poly(4)),
      timing: Animated.timing,
      useNativeDriver: false,
    },
    screenInterpolator: sceneProps => {
      const { layout, position, scene } = sceneProps

      const thisSceneIndex = scene.index
      const width = layout.initWidth

      const translateX = position.interpolate({
        inputRange: [thisSceneIndex - 1, thisSceneIndex],
        outputRange: [width, 0],
      })

      return { transform: [ { translateX } ] }
    },
  }
}

const StackNavigator = createStackNavigator(
  {
    FluidTransitionNavigator: {
      screen: FluidTransitionNavigator
    },
    Dashboard: {
      screen: Dashboard
    }
  },
  {
    initialRouteName: 'FluidTransitionNavigator',
    headerMode: 'float',
    navigationOptions: (props) => ({
      header: renderHeader(props)
    }),
    transitionConfig: transitionConfig
  }
);

const renderHeader = (props) => {
  let index = props.navigation.state.index;

  const logout = (props.navigation.state.routeName === 'Dashboard');
  let title = '';
  switch (props.navigation.state.routeName) {
    case 'Dashboard':
      title = 'Dashboard';
      break;
    case 'FluidTransitionNavigator':
      if (index !== undefined) {
        switch (props.navigation.state.routes[index].routeName) {
          case 'Login':
            title = 'Sign In';
            break;
          case 'SignInOrRegister':
            title = 'SignInOrRegister';
            break;
          default:
            title = '';
        }
      }
      break;
    default:
      title = '';
  }

  return (['SignInOrRegister', 'Sign In'].includes(title)) ? null : (
    <ThemeContext.Provider value={getTheme(uiTheme)} >
      <UniToolbar navigation={props.navigation} toolbarTitle={title} logout={logout} />
    </ThemeContext.Provider>
  );
};

renderHeader.propTypes = {
  navigation: PropTypes.object
};

const uiTheme = {
    toolbar: {
        container: {
          ...Platform.select({
            ios: {
              height: 70
            },
            android: {
              height: 76
            }
          })
        },
    },
};

export default StackNavigator;

下面是我的测试:

StackNavigator.test.js

import React from "react";
import renderer from "react-test-renderer";
import StackNavigator from "../StackNavigator";

test("renders correctly", () => {
  const tree = renderer.create(<StackNavigator />).toJSON();
  expect(tree).toMatchSnapshot();
});

我已经在这里看到了类似的几乎相同的问题 : 玩笑快照测试失败是由于反应生成的导航键

接受答案仍然没有回答我的问题。 但是它没有导致我失望另一只兔子洞:

我试图使用内联匹配: expect(tree).toMatchInlineSnapshot()以生成运行后的树yarn run test:unit ,然后试图插入Any <String>代替所有键。 这没有遗憾的工作。

我难倒。 我不知道如何解决这个问题。 我已经搜查,搜查,试图多的事情要解决它,我不能解决这个问题。

请能有人帮我一把?

Answer 1:

我解决我的问题,但不是嘲笑Date.now这是在其他许多情况下建议。

相反,我适应了我的答案上找到https://github.com/react-navigation/react-navigation/issues/2269#issuecomment-369318490用户名为joeybaker。

这样做的理由是给出如下:

键是不是你的测试目的很重要。 你真正关心的是路线和索引。

他的代码如下,并假设使用的终极版动作和减速器:

// keys are date and order-of-test based, so just removed them
const filterKeys = (state) => {
  if (state.routes) {
    return {
      ...state,
      routes: state.routes.map((route) => {
        const { key, ...others } = route
        return filterKeys(others)
      }),
    }
  }
  return state
}

it('clears all other routes', () => {
    const inputState = {}
    const action = { type: AUTH_LOGOUT_SUCCESS }
    const state = filterKeys(reducer(inputState, action))
    expect(state.routes).toBe........
})

我已经适应了这样我的情况(我不使用终极版还)如下:

test("renders correctly", () => {

  const tree = renderer.create(<StackNavigator />);
  const instance = tree.getInstance();
  const state = filterKeys(instance.state.nav);

  expect(state).toMatchSnapshot();
});

// keys are date and order-of-test based, so just removed them
const filterKeys = (state) => {
  if (state.routes) {
    return {
      ...state,
      routes: state.routes.map((route) => {
        const { key, ...others } = route
        return filterKeys(others);
      }),
    }
  }
  return state;
};

这被渲染的测试看起来是这样的:

// Jest Snapshot v1

exports[`renders correctly 1`] = `
Object {
  "index": 0,
  "isTransitioning": false,
  "key": "StackRouterRoot",
  "routes": Array [
    Object {
      "index": 0,
      "isTransitioning": false,
      "routeName": "FluidTransitionNavigator",
      "routes": Array [
        Object {
          "routeName": "SignInOrRegister",
        },
      ],
    },
  ],
}
`;


文章来源: Snapshot test with Jest on nested react-navigation component - Object keys change so Snapshot match fails