假设我们有这个无状态组件
import React from ‘react’;
const HelloWorld = ({name}) => (
const sayHi = event => {
alert(`Hi ${name}`);
}
return (
<div>
<a
href="#"
onClick={sayHi}>Say Hi</a>
</div>
);
);
export default HelloWorld;
测试 sayHi
功能的最佳方法是什么?
知道我要为它做单元测试。
最佳答案
如果您只看 Jest docs,这应该非常简单.您基本上想要模拟点击并模拟/监视 alert
调用。
大致是这样的:
import React from 'react';
import {shallow} from 'enzyme';
test('that alert is called when clicking link', () => {
const testName = 'Jack';
// Render a checkbox with label in the document
const hw = shallow(
<HelloWorld name={testName} />
);
const alert = jest.fn();
hw.find('a').simulate('click');
expect(alert).toBeCalledWith('Hi ' + testName);
});
关于javascript - 测试私有(private)无状态组件功能的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41587188/