import React, { Component } from 'react';
import { shallow } from 'enzyme';
class App extends Component {
a = {
func: () => 1
};
render () {
return null;
}
}
describe('<App>', () => {
test('func()', () => {
const app = shallow(<App />),
func_spy = jest.spyOn(???);
});
});
我想监视func
类属性中的a
函数。我可以使用spyOn
方法或其他方法实现它吗?预先感谢您的答复。
答案 0 :(得分:1)
您可以使用.instance
获取类实例,并使用它来创建间谍:
import React, { Component } from 'react';
import { shallow } from 'enzyme';
class App extends Component {
a = {
func: () => 1
};
render() {
return null;
}
}
describe('<App>', () => {
test('func()', () => {
const app = shallow(<App />);
const instance = app.instance(); // <= get the instance
const func_spy = jest.spyOn(instance.a, 'func'); // <= spy on instance.a.func
instance.a.func();
expect(func_spy).toHaveBeenCalled(); // Success!
});
});