正确模拟以下示例的最佳方法是什么?
问题是在导入时间之后,foo保持对原始未引用的引用bar.
module.js:
export function bar () {
return 'bar';
}
export function foo () {
return `I am foo. bar is ${bar()}`;
}
Run Code Online (Sandbox Code Playgroud)
module.test.js:
import * as module from '../src/module';
describe('module', () => {
let barSpy;
beforeEach(() => {
barSpy = jest.spyOn(
module,
'bar'
).mockImplementation(jest.fn());
});
afterEach(() => {
barSpy.mockRestore();
});
it('foo', () => {
console.log(jest.isMockFunction(module.bar)); // outputs true
module.bar.mockReturnValue('fake bar');
console.log(module.bar()); // outputs 'fake bar';
expect(module.foo()).toEqual('I am foo. bar is fake bar');
/**
* …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试一个 React 组件并确保当它的按钮被点击时,正确的方法被调用。但是,当我尝试运行我的测试并尝试监视该方法时,我收到以下消息:
错误:无法监视原始值;给定的未定义
如何测试单击按钮时是否调用了正确的方法?谢谢!
示例组件.jsx:
import * as React from 'react';
const SampleComponent = () => {
const sampleMethod = () => {
console.log('hello world');
};
return <button onClick={sampleMethod} type="button">Click Me</button>;
};
export default SampleComponent;
Run Code Online (Sandbox Code Playgroud)
sampleComponent.test.jsx:
import * as React from 'react';
import { shallow } from 'enzyme';
import SampleComponent from './sample';
test('testing spy', () => {
const spy = jest.spyOn(SampleComponent.prototype, 'sampleMethod');
const wrapper = shallow(<SampleComponent />);
wrapper.find('button').simulate('click');
expect(spy).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)