问题
I'm fairly new to React, so please forgive my ignorance. I have a component:
const Login: FunctionComponent = () => {
const history = useHistory();
//extra logic that probably not necessary at the moment
return (
<div>
<form action="">
...form stuff
</form>
</div>
)
}
When attempting to write jest/enzyme test, the one test case I've written is failing with the following error ` › encountered a declaration exception
TypeError: Cannot read property 'history' of undefined`
I've tried to use jest to mock useHistory like so:
jest.mock('react-router-dom', () => ({
useHistory: () => ({ push: jest.fn() })
}));
but this does nothing :( and I get the same error. Any help would be most appreciated
UPDATE:
So I figured it out. I was on the right path creating a mock for the useHistory()
hook, I defined in the wrong place. Turns the mock needs to be define (at least for useHistory) outside of the scope of the test methods, ex:
import { shallow } from 'enzyme';
import React from 'react';
import Login from './app/componets/login.component';
jest.mock('react-router', () => ({
...jest.requireActual('react-router'),
useHistory: () => ({ push: jest.fn() })
}));
/**
* Test suite describing Login test
describe('<LoginPage>', () => {
test('should test something', () => {
//expect things to happen
});
})
With the above test runs without failing on history being undefined.
回答1:
So I figured it out. I was on the right path creating a mock for the useHistory() hook, I defined in the wrong place. Turns the mock needs to be define (at least for useHistory) outside of the scope of the test methods, ex:
import { shallow } from 'enzyme';
import React from 'react';
import Login from './app/componets/login.component';
jest.mock('react-router', () => ({
...jest.requireActual('react-router'),
useHistory: () => ({ push: jest.fn() })
}));
/**
* Test suite describing Login test
describe('<LoginPage>', () => {
test('should test something', () => {
//expect things to happen
});
})
With the above, the test runs without failing on history being undefined.
来源:https://stackoverflow.com/questions/60404319/react-jest-enzyme-testing-usehistory-hook-breaks-test