mount 返回的包装器有 .instance() => ReactComponent 方法。仅适用于类组件。
返回单节点包装器的节点的底层类实例。
index.tsx:
import React, { Component } from 'react';
const MyContext = React.createContext({
otherFunction: (value) => {
console.log(value);
},
});
export class MyComponent extends Component {
static contextType = MyContext;
myFunction() {
this.context.otherFunction('shouldBecorrectValue');
}
render() {
return <div>my component</div>;
}
}
index.test.tsx:
import { mount } from 'enzyme';
import React from 'react';
import { MyComponent } from './';
describe('69127076', () => {
test('should pass', () => {
const logSpy = jest.spyOn(console, 'log');
const wrapper = mount(<MyComponent />);
wrapper.instance()['myFunction']();
expect(logSpy).toBeCalledWith('shouldBecorrectValue');
logSpy.mockRestore();
});
});
测试结果:
PASS examples/69127076/index.test.tsx (10.228 s)
69127076
✓ should pass (47 ms)
console.log
shouldBecorrectValue
at console.<anonymous> (node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866:25)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.tsx | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.804 s
软件包版本:
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"react": "^16.14.0",
"react-dom": "^16.14.0",