如何在快照测试中模拟动态值?

时间:2019-09-12 13:40:57

标签: reactjs unit-testing jestjs snapshot

我必须进行快照测试:

  1. 我使用自定义路由器(用于保护登录用户的防护)从路由器页面创建快照,并且每次运行此测试时,都会生成不同的密钥。
  2. 我在日期选择器中有新的Date(),该如何模拟呢? 重新分配全局。日期对我不起作用

  3. 1。
const ProtectedRoute = ({ isAllowed, ...props }) => (isAllowed
  ? <Route {...props} />
  : <Redirect to="/login" />);

const LoginProtectedRoute = ({ isAllowed, ...props }) => (isAllowed
  ? <Route {...props} />
  : <Redirect to="/" />);

const WebClient = (props: any) => {
  const { userTokenController } = props;
  return (
    <Router>
      <div>
        <Switch>
          <ProtectedRoute
            exact
            path="/"
            component={HomePage}
            isAllowed={UserTokenRepo().getUserAuth(userTokenController)}
          />
          {/* <Route path="/login" component={Login} /> */}
          <LoginProtectedRoute
            path="/login"
            component={Login}
            isAllowed={!UserTokenRepo().getUserAuth(userTokenController)}
          />
          <ProtectedRoute
            path="/ResourceManagement"
            component={ResourceManagement}
            isAllowed={UserTokenRepo().getUserAuth(userTokenController)}
          />
        </Switch>
      </div>
    </Router>
  );
};

                        "goForward": [Function],
                        "length": 1,
                        "listen": [Function],
                        "location": Object {
                          "hash": "",
    -                     "key": "gsde51",
    +                     "key": "q67i5b",
                          "pathname": "/login",
                          "search": "",
                          "state": undefined,
                        },

  1.                 <Calendar readOnlyInput view="month" dateFormat="mm/yy" value={startDate} onChange={this.handleChange} yearNavigator yearRange="2010:2030" />
    
    
    -                   value={2019-09-12T11:16:56.134Z}
    +                   value={2019-09-12T13:31:32.598Z}

1 个答案:

答案 0 :(得分:0)

将实际值与实际快照测试分离。

无耻地从this medium article中拉出。.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import renderer from 'react-test-renderer';
import moment from 'moment-timezone';


it('renders without crashing', () => {
  moment.tz.setDefault('EST');
  let props = {
    currentDay: moment("2017-09-15 09:30:00").format("MMM Do YYYY h:mm:ss a")
  };

  const tree = renderer.create(<App {...props} />).toJSON();
  expect(tree).toMatchSnapshot();
});