gpt4 book ai didi

Jest Error: Uncaught [TypeError: Cannot read properties of undefined (reading 'then')](JEST错误:未捕获[TypeError:无法读取未定义的属性(正在读取‘THEN’)])

转载 作者:bug小助手 更新时间:2023-10-25 23:34:30 26 4
gpt4 key购买 nike



I have situation in my unit test case for a react typescript application, where in my logout function the mocked persistor is returning undefined. bellow are the test and relevant files definitions:

我在Reaction类型脚本应用程序的单元测试用例中遇到过这样的情况,在我的注销函数中,被嘲弄的持久器返回未定义的。下面是测试和相关文件的定义:


logout function definition:

注销函数定义:


import { AnyAction } from '@reduxjs/toolkit';
import { Dispatch } from 'react';
import { Persistor } from 'redux-persist';

import * as AuthAction from '../../stores/auth/AuthAction';

export const logout = (persistor: Persistor) => (dispatch: Dispatch<AnyAction>) => {
console.log('***persistor***:', persistor.purge());
persistor
.purge()
.then((response) => {
dispatch(AuthAction.resetAuth());
})
.catch((error) => {
console.log(error);
})
.finally(() => {
// always executed
});
};

Now when I run the tests, it throws me error as “ TypeError: Cannot read properties of undefined (reading 'then')"

现在,当我运行测试时,它抛出的错误是“TypeError:Cannot Read Property of Unfined(Reding‘THEN’)”


   8 |   console.log('***persistor***:', persistor.purge());
9 | persistor
> 10 | .purge()
| ^
11 | .then((response) => {
12 | dispatch(AuthAction.resetAuth());
13 | })

I'm also logging the the persistor, but for some reason it's returning undefined. I'm not able to figure this one out. Please suggest, the test is defined bellow:

我也在记录持久器,但出于某种原因,它返回未定义的。我搞不懂这件事。请建议,测试定义如下:


import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import React from 'react';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
import { Persistor } from 'redux-persist/lib/types';
import thunk from 'redux-thunk';

import IAuthState from '../../../stores/auth/models/IAuthState';
import SessionTimeout from './SessionTimeout';

jest.useFakeTimers();

describe('SessionTimeout', () => {
const tempPersistor = {
persist: jest.fn(),
purge: jest.fn().mockImplementation(() => Promise.resolve()), // Return a resolved promise
} as unknown as Persistor;

const setup = (persistor: Persistor) => {
console.log('persistor.purge(): ', persistor.persist());
interface IStore {
auth: IAuthState;
}
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
const store = mockStore({
auth: {
wbsAccessToken: 'some wbsAccessToken',
wbsRefreshToken: 'some wbsRefreshToken',
wbsRefreshExp: 0,
wbsAccessExp: 0,
user: {
id: -1,
image: ' some image',
firstName: 'some firstName',
lastName: 'some lastName',
email: 'some email',
verified: false,
},
} as IAuthState,
} as IStore);

return render(
<Provider store={store}>
<SessionTimeout auth={(store.getState() as IStore).auth} persistor={persistor} />{' '}
</Provider>
);
};

beforeEach(() => {
jest.useFakeTimers();
// Mocking the event listeners
jest.mock('react-redux');
jest.mock('../../../utilities/eventListenerUtil', () => ({
addEventListeners: jest.fn(),
removeEventListeners: jest.fn(),
}));
setup(tempPersistor);
});

// Running all pending timers and switching to real timers using Jest
afterEach(() => {
jest.clearAllTimers();
jest.runOnlyPendingTimers();
jest.useRealTimers();
});

test('should render without crashing', () => {
expect(screen).toBeDefined();
});

it('should render the modal with the session timeout message', async () => {
// Advance timers to simulate inactivity and trigger the warning
act(() => {
jest.advanceTimersByTime(61000); // Simulate 1.0166667 minute passing
});

expect(screen.queryByText('Session Timeout')).toBeInTheDocument();
expect(screen.queryByText(/You're being timed out due to inactivity/i)).toBeInTheDocument();

expect(true);
});

it('should log off when clicking "Log Off" button', async () => {
// Advance timers to simulate inactivity and trigger the warning
act(() => {
jest.advanceTimersByTime(61000); // Simulate 1.0166667 minute passing
});

await fireEvent.click(screen.getByText('Log Off'));

// Wait for the logout process to complete
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0)); // Allow microtasks to run
expect(tempPersistor.persist).toHaveBeenCalled();
});
});

更多回答
优秀答案推荐
更多回答

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