У меня проблемы с тестированием, если в моем компоненте был вызван history.pu sh. Когда я удаляю await logout()
в моем компоненте MainNavigation, тест проходит. Однако, когда await logout()
есть, тест не пройден. Может кто-нибудь объяснить мне, почему это происходит?
Контрольный пример
jest.mock('../../repositories/authenticationRepository');
import { logout } from '../../repositories/authenticationRepository';
import history from '../../sitehistory';
let initialStateMock;
beforeEach(() => {
initialStateMock = {
isNavigationOpen: true
};
});
it('Redirects the user to the login page after logout', () => {
logout.mockReturnValue(Promise.resolve('Response'));
history.push = jest.fn();
const wrapper = mount(
<StateProvider initialState={initialStateMock} reducer={reducer}>
<Router>
<MainNavigation />
</Router>
</StateProvider>
);
wrapper.find('#btn-logout').simulate('click');
expect(history.push).toHaveBeenCalledTimes(1);
expect(history.push).toHaveBeenCalledWith('/login');
});
аутентификацияRepository. js
import axios from 'axios';
import config from '../settings';
const logout = async () => axios.delete(`${config.API_URL}/user/logout`);
export {
logout
};
siteHistory. js
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
history.listen(async (location, action) => {
});
export default history;
MainNavigation. js
class MainNavigation extends Component {
static contextType = StateContext;
handleLogout = async () => {
await logout(); //Test passes when this line is removed
history.push('/login');
}
render() {
const [{ isNavigationOpen }, dispatch] = this.context;
return (
<nav id="main-navigation" className={`navigation ${isNavigationOpen ? 'navigation-open' : 'navigation-closed'}`}>
<small><button id="btn-logout" type="button" className="btn btn-link" onClick={this.handleLogout}>Logout</button></small>
</nav>
);
}
}
export default MainNavigation;