gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:02:41 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com