我是单元测试的新手,正在研究一个我非常困惑的示例问题。
在下面的例子中,我需要测试是否在调用onSubmitHandler之后调用函数onPost,前提是employee的boolean值为true。
class Employee extends React.Component{
function onSubmitHandler(){
if(employee){
this.onPost()
}
else {
this.onFailure()
}
}
function onPost(){
return something
}
function onFailure(){
return something
}
render(){
return(<EmployeeForm onAdd = {onSubmitHandler} />
)
}
}
以下是我创建的测试。
test('onPost is called',()=>{
const wrapper = shallow (<Employee/>)
wrapper.instance().onSubmitHandler()
Employee.onPost= jest.fn()
expect(Employee.onPost).toBeCalled()
})
这个测试失败了,我想知道我是否可以对如何测试该功能做一些澄清。谢谢。
答案 0 :(得分:3)
首先,提供有关Employee组件的更多详细信息,谁是onSubmitHandler函数中的employee变量?你怎么设置它? 关于您的测试,首先您需要使用shallow来获取渲染组件的包装,然后获取组件的实例,以便您可以测试所需的一切:
test("onPost is called", () => {
const wrapper = shallow(<Employee />)
const instance = wrapper.instance()
instance.onPost = jest.fn()
instance.onSubmitHandler()
expect(instance.onPost).toBeCalled()
});
由于您的组件过于简单,我可以理解您的需求,并且我提供了一个完整的示例测试您的Employee组件的类型脚本和更好的方法来测试是否使用 jest.spyOn < / em>的
1 - 员工组件
import * as React from "react";
export interface Employee {
id: number;
name: string;
}
interface Props {
employee: Employee;
}
export default class EmployeeComp extends React.Component<Props> {
constructor(props: Props) {
super(props);
}
onSubmitHandler = () => {
if (this.props.employee) {
this.onPost();
} else {
this.onFailure();
}
};
onPost = () => {
return true;
};
onFailure = () => {
return false;
};
render() {
return <div>Some content</div>;
}
}
2 - 完成测试
import * as React from "react";
import { shallow } from "enzyme";
import EmployeeComp, { Employee } from "src/some";
const employee: Employee = {
id: 10,
name: "Mario 64"
};
describe("Employee component", () => {
it("should render", () => {
const wrapper = shallow(<EmployeeComp employee={employee} />);
expect(wrapper).toBeDefined();
expect(wrapper.find("div").length).toBe(1);
});
it("should call onPost method when has employee", () => {
const wrapper = shallow(<EmployeeComp employee={employee} />);
const instance: EmployeeComp = wrapper.instance() as EmployeeComp;
const spy = jest.spyOn(instance, "onPost");
instance.onSubmitHandler();
expect(spy).toHaveBeenCalledTimes(1);
});
it("should call onFailure method when has NO employee", () => {
const wrapper = shallow(<EmployeeComp employee={null} />);
const instance: EmployeeComp = wrapper.instance() as EmployeeComp;
const spy = jest.spyOn(instance, "onFailure");
instance.onSubmitHandler();
expect(spy).toHaveBeenCalledTimes(1);
});
});