开玩笑的模拟文件的变量和更改函数的行为

时间:2019-03-21 07:38:47

标签: reactjs jestjs

我想为我的路由器编写测试用例。我有想要在测试用例中模拟的const对象。如何在测试文件中更改用户对象。

const user = {
  isAuthenticated: true
};

export const PrivateRoute = ({ component: Component, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props =>
        user.isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );
};

test.js

it("should return login route", () => {
    const route = <PrivateRoute path="/" component={()=>{}} />
    expect(route)..toMatchSnapshot();
});

it("should return home route", () => {
    const route = <PrivateRoute path="/" component={()=>{}} />
    expect(route)..toMatchSnapshot();
});

1 个答案:

答案 0 :(得分:0)

user应该在模块外部可用,以实现可测试性:

export const user = {
  isAuthenticated: true
};

通过这种方式可以在测试中对其进行模拟

user.isAuthenticated = false;

应保留原始值,以免交叉污染测试:

let originalIsAuthenticated;

beforeEach(() => {
  originalIsAuthenticated = user.isAuthenticated;
});

afterEach(() => {
  user.isAuthenticated = originalIsAuthenticated;
});