簡體   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