繁体   English   中英

Jest 模拟服务 variable.asObservable 返回

[英]Jest mocking service variable.asObservable return

我是一名初级开发人员,使用 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM