当Component.prototype返回undefined时,使用jest/enzyme对componentDidMount进行单元测试的方法如下:
npm install jest enzyme enzyme-adapter-react-16 react-test-renderer --save-dev
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from './MyComponent';
describe('MyComponent', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<MyComponent />);
});
afterEach(() => {
jest.clearAllMocks();
});
it('should call componentDidMount', () => {
const componentDidMountSpy = jest.spyOn(MyComponent.prototype, 'componentDidMount');
wrapper.instance().componentDidMount();
expect(componentDidMountSpy).toHaveBeenCalled();
});
// 其他的测试用例...
});
在上面的示例中,我们首先导入所需的库和组件。然后,在beforeEach
中使用shallow
方法来创建组件的浅渲染。这里使用beforeEach
的原因是希望在每个测试用例开始之前都能够得到一个干净的测试环境。
然后,在it
块中,我们首先使用jest.spyOn
来监听componentDidMount
方法是否被调用。然后,我们调用componentDidMount
方法,并使用expect
断言来验证componentDidMountSpy
是否被调用。
最后,在afterEach
中使用jest.clearAllMocks
来清除所有的mock。
这样,我们就可以使用jest/enzyme对componentDidMount进行单元测试了。
需要注意的是,上述示例中的MyComponent
是一个示例组件,你需要将其替换为你要测试的组件。另外,如果你的组件中使用了异步操作,可能需要使用async/await
或其他方法来处理异步代码的测试。
领取专属 10元无门槛券
手把手带您无忧上云