在React中导出箭头函数,用于Jest中的单元测试

s71maibg  于 2023-04-03  发布在  Jest
关注(0)|答案(1)|浏览(128)

我一直得到的错误是checkIfBlank是未定义的,我知道我必须导出函数,但我不知道如何为箭头函数
下面是我在register.js中的函数

import React from "react";
import axios from 'axios';
import bycrypt from 'bcryptjs';

import { Link } from "react-router-dom";

import { Helmet } from "react-helmet";

import { useState } from "react";
// const bcrypt = require('bcryptjs');

import InputBoxForInfo from "../components/input-box-for-info";
import Button from "../components/button";
import "./register.css";

const Register = (props) => {
  const [name, setName] = useState("");
  const [surname, setSurname] = useState("");
  const [email, setEmail] = useState("");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const salt = bycrypt.genSaltSync(10);
  const hashedPassword = bycrypt.hashSync(password,salt);
  const[exist, setExistence] = useState("");
  const [errorMessage, setErrorMessage] = useState('');
  const postDetails = () =>{
    axios.post("http://localhost:3002/api/post/register",{name:name, surname:surname, email: email, username: username, password: hashedPassword});
    setTimeout(function(){
    window.location.href = 'http://localhost:3000/login';
    }, 1000);
    
  }

  const checkIfUserExists = () =>{
    axios
    .get("http://localhost:3002/api/get/doesExist/" + username)
    .then(function(response){
      const userExists = response.data;
      console.log(response.data);
      if (JSON.stringify(userExists) == "[]"){
        setErrorMessage('Account created successfully');
        postDetails();
      }
      else{
        setErrorMessage('Username already exists');
      }
    });
  }

  
   const checkIfBlank=()=>{
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const passwordPattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/;

    //If fields empty, warn
    if(name == "" || surname =="" || email == "" || username == "" || password==""){
      alert("Please enter all details");
    }

    //not empty
    else{
      //check if email correct and password is strong
      if(emailPattern.test(email) && passwordPattern.test(password)){
        checkIfUserExists();
      }
      //otherwise warn
      else{
        //email not corect format
        if(!emailPattern.test(email)){
          setErrorMessage('Please enter a valid email');
        }
        if(!passwordPattern.test(password)){
          setErrorMessage("Please enter a stronger password");
        }
      }
    }
  }

  const handleRegister = () => {
    // Do something with the input values
    console.log(
      `Name: ${name}, Surname: ${surname} Email: ${email}, Username: ${username}, Password: ${hashedPassword}`
    );
    checkIfBlank();
  };
  

  return (
    <div className="register-container">
      <Helmet>
        <title>register - Project ARENA</title>
        <meta property="og:title" content="register - Project ARENA" />
      </Helmet>
      <div className="register-container1">
        <Link to="/" className="register-navlink">
          <svg
            viewBox="0 0 877.7142857142857 1024"
            className="register-backbtn"
          >
            <path d="M519.429 797.143l58.286-58.286c14.286-14.286 14.286-37.143 0-51.429l-175.429-175.429 175.429-175.429c14.286-14.286 14.286-37.143 0-51.429l-58.286-58.286c-14.286-14.286-37.143-14.286-51.429 0l-259.429 259.429c-14.286 14.286-14.286 37.143 0 51.429l259.429 259.429c14.286 14.286 37.143 14.286 51.429 0zM877.714 512c0 242.286-196.571 438.857-438.857 438.857s-438.857-196.571-438.857-438.857 196.571-438.857 438.857-438.857 438.857 196.571 438.857 438.857z"></path>
          </svg>
        </Link>
      </div>
      <div className="register-container5">
        <span className="register-text">
          <span>Register</span>
          <br></br>
        </span>

        <InputBoxForInfo
          buttonText="NAME"
          onChange={(e) => setName(e.target.value)}
          rootClassName="input-box-for-info-root-class-name"
        ></InputBoxForInfo>

        <InputBoxForInfo
          buttonText="SURNAME"
          onChange={(e) => setSurname(e.target.value)}
          rootClassName="input-box-for-info-root-class-name2"
        ></InputBoxForInfo>
    
        <InputBoxForInfo
          buttonText="EMAIL"
          onChange={(e) => setEmail(e.target.value)}
          rootClassName="input-box-for-info-root-class-name3"
        ></InputBoxForInfo>
    
        <InputBoxForInfo
          buttonText="USERNAME"
          onChange={(e) => setUsername(e.target.value)}
          rootClassName="input-box-for-info-root-class-name4"
        ></InputBoxForInfo>
    
        <InputBoxForInfo
          buttonText="PASSWORD"
          onChange={(e) => setPassword(e.target.value)}
          isPassword
          rootClassName="input-box-for-info-root-class-name5"
        ></InputBoxForInfo>
    
        <br></br>
        <Button 
          name="Register"
          onClick={() => {
            console.log("Register button clicked");
            handleRegister();
          }}
          rootClassName="button-root-class-name"
        ></Button>
        
        <br></br>
        {errorMessage && <div className="error">{errorMessage}</div>}
        <span className="register-text3">Already have an account?</span>
        <Link to="/login" className="register-navlink1 button">
          Login here
        </Link>
      </div>
    </div>
  );
};

export default Register;

下面是我对上述代码的单元测试

import React  from 'react';
import Register from './register';

// Import the necessary modules
const axios = require('axios');

// Import the function to be tested
import { checkIfBlank } from './register.js';
//const { checkIfBlank } = require('./register');

// Test suite for checkIfBlank function
describe('checkIfBlank', () => {

  // Mock the setErrorMessage and postDetails functions
  let setErrorMessage = jest.fn();
  let postDetails = jest.fn();

  // Test case when all fields are filled in and valid
  test('valid input', () => {
    // Set up the input data
    const name = 'John';
    const surname = 'Doe';
    const email = 'john.doe@example.com';
    const username = 'johndoe';
    const password = 'Passw0rd';

    // Call the function
    checkIfBlank(name, surname, email, username, password, setErrorMessage, postDetails);

    // Check that setErrorMessage and postDetails were not called
    expect(setErrorMessage).not.toHaveBeenCalled();
    expect(postDetails).not.toHaveBeenCalled();
  });

  // Test case when one or more fields are empty
  test('missing field', () => {
    // Set up the input data
    const name = '';
    const surname = 'Doe';
    const email = 'john.doe@example.com';
    const username = 'johndoe';
    const password = 'Passw0rd';

    // Call the function
    checkIfBlank(name, surname, email, username, password, setErrorMessage, postDetails);

    // Check that setErrorMessage was called with the correct message
    expect(setErrorMessage).toHaveBeenCalledWith('Please enter all details');

    // Check that postDetails was not called
    expect(postDetails).not.toHaveBeenCalled();
  });

  // Test case when the email is invalid
  test('invalid email', () => {
    // Set up the input data
    const name = 'John';
    const surname = 'Doe';
    const email = 'johndoe@examplecom';
    const username = 'johndoe';
    const password = 'Passw0rd';

    // Call the function
    checkIfBlank(name, surname, email, username, password, setErrorMessage, postDetails);

    // Check that setErrorMessage was called with the correct message
    expect(setErrorMessage).toHaveBeenCalledWith('Please enter a valid email');

    // Check that postDetails was not called
    expect(postDetails).not.toHaveBeenCalled();
  });

  // Test case when the password is weak
  test('weak password', () => {
    // Set up the input data
    const name = 'John';
    const surname = 'Doe';
    const email = 'john.doe@example.com';
    const username = 'johndoe';
    const password = 'password';

    // Call the function
    checkIfBlank(name, surname, email, username, password, setErrorMessage, postDetails);

    // Check that setErrorMessage was called with the correct message
    expect(setErrorMessage).toHaveBeenCalledWith('Please enter a stronger password');

    // Check that postDetails was not called
    expect(postDetails).not.toHaveBeenCalled();
  });
});

我尝试了以下方法:
这在regiter.js中的函数export const checkIfBlank=()=>{
在register.js的末尾添加regsiter.js export {checkIfBlank};的开头
在register.js的末尾添加regsiter.js module.exports = { checkIfBlank };的开头
这在regiter.js中的函数module.exports = checkIfBlank=()=>{

iklwldmw

iklwldmw1#

您尝试导入两个不同的方法,但您已将Register函数声明为默认导出:export default Register .
如果你想导出Register函数和checkIfBlank函数,你需要将你的导出改为列表:

export {
  Register,
  checkIfBlank
}

现在,当你导入你需要做的方法时:

import { Register, checkIfBlank } from './register';

您可以在mdn docs here中阅读有关export关键字的更多信息。

相关问题