javascript - 开 Jest mock 服务变量.asObservable 返回

标签 javascript reactjs unit-testing mocking jestjs

我是一名初级开发人员,正在使用 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(),
  // ...
};

最佳答案

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

privateRoute.tsx:

import React from 'react';
import { Route, Redirect } from 'react-router';
import { authenticationService } from './authenticationService';

export const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={(props) => {
      const currentUser = authenticationService.currentUser;
      if (!currentUser) {
        return <Redirect to={{ pathname: '/', state: { from: props.location } }} />;
      }
      return <Component {...props} />;
    }}
  />
);

authenticationService.ts:

export const authenticationService = {
  currentUser: {},
};

privateRoute.test.ts:

import React from 'react';
import { PrivateRoute } from './privateRoute';
import { mount, shallow } from 'enzyme';
import { MemoryRouter, Redirect, Router } from 'react-router';
import { authenticationService } from './authenticationService';

describe('59825407', () => {
  it('should render component if current user exists', () => {
    const mProps = { component: jest.fn().mockReturnValueOnce(null) };
    const wrapper = mount(
      <MemoryRouter>
        <PrivateRoute {...mProps}></PrivateRoute>
      </MemoryRouter>,
    );
    expect(wrapper.find(mProps.component).props()).toEqual(
      expect.objectContaining({
        history: expect.any(Object),
        location: expect.any(Object),
        match: expect.any(Object),
      }),
    );
  });

  it('should redirect if current user does not exist ', () => {
    authenticationService.currentUser = undefined as any;
    const mProps = { component: jest.fn().mockReturnValueOnce(null), path: '/user' };
    const wrapper = mount(
      <MemoryRouter initialEntries={['/user']}>
        <PrivateRoute {...mProps}></PrivateRoute>
      </MemoryRouter>,
    );
    const history = wrapper.find('Router').prop('history') as any;
    expect(history.location.state.from.pathname).toBe('/user');
    expect(history.location.pathname).toBe('/');
  });
});

100%覆盖率的单元测试结果:

 PASS  src/stackoverflow/59825407/privateRoute.test.tsx (16.491s)
  59825407
    ✓ should render component if current user exists (74ms)
    ✓ should redirect if current user does not exist  (12ms)

--------------------------|----------|----------|----------|----------|-------------------|
File                      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
--------------------------|----------|----------|----------|----------|-------------------|
All files                 |      100 |      100 |      100 |      100 |                   |
 authenticationService.ts |      100 |      100 |      100 |      100 |                   |
 privateRoute.tsx         |      100 |      100 |      100 |      100 |                   |
--------------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        18.683s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59825407

关于javascript - 开 Jest mock 服务变量.asObservable 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59825407/

相关文章:

javascript - 传递 props 时我应该总是写 this.props 吗?

javascript - useState Hook 不更新值

reactjs - React 测试库中的 QuerySelectorAll?

java - 对仅调用 lambda 表达式链中的其他方法的 java 方法进行单元测试

java - 如何使用 Mockito 在另一个 Mock 类中模拟 Spring 消息资源?

Javascript OOP,不会给我错误,但代码不起作用

javascript - 如何在当前位置上方添加HTML内容而不跳转页面

React float-left 中的 Html 不起作用

reactjs - 如何使用 <Link> react 路由器?

c# - MSpec 替代 winrt 应用程序中的 BDD 样式单元测试