在Login
功能组件中,我有一个函数validateForm
,它检查username
和password
的长度是否大于零。
function validateForm() {
return username.length > 0 && password.length > 0;
}
我使用Jest作为单元测试工具。
import React from "react";
import Login, { validateForm } from "./Login";
import { render, screen } from "@testing-library/react";
describe("LoginUser", () => {
test("validate username and password should be greater than 0", () => {
var username = "name";
var password = "pass";
expect(validateForm(username.length)).toBeGreaterThan(0);
});
});
TypeError: (0 , _Login.validateForm) is not a function
我在运行测试用例时遇到了上述错误。如何解决此错误?
看起来你忘了导出它:
...
export function validateForm() {
return username.length > 0 && password.length > 0;
}
...
但是,如果validateForm
是在Login组件(函数(的主体内定义的,请考虑将其移出并单独导出,以使此测试工作正常。
// Put outside and export:
export function validateForm(username, password) {
return username.length > 0 && password.length > 0;
}
const Login = (props) => {
// And remove from here.
// function validateForm() {
// return username.length > 0 && password.length > 0;
// }
// use this variable in the component.
const isFormValid = validateForm(username, password);
return ...
}
export default Login;