嘲笑服务变量。asObservable返回

问题描述 投票:0回答:1

我是使用Jest作为单元测试框架的React应用程序的初级开发人员

我必须测试我的privateRoute文件:

export const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props => {
      const currentUser = authenticationService.currentUser;
      if (!currentUser) {
        // not logged in so redirect to login page with the return url
        return (
          <Redirect to={{ pathname: "/", state: { from: props.location } }} />
        );
      }

      // authorized so return component
      return <Component {...props} />;
    }}
  />
);

返回之前我无法测试条件if (!currentUser) {

您是否对如何测试此行有任何建议?

我尝试使用jest.fn模拟authenticationService.currentUser,但没有成功

这是authenticationService的一段代码:

const currentUserSubject = new BehaviorSubject(
  JSON.parse(localStorage.getItem("currentUser"))
);

export const authenticationService = {
  // ...
  currentUser: currentUserSubject.asObservable(),
  // ...
};
javascript unit-testing mocking jestjs
1个回答
0
投票

使用PrivateRoute模块的enzyme组件的单元测试解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.