Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I'm updated my react-native project-v0.73.4 with jest-v29.6.3 after my api test cases are failing. #14999

Open
DeepakSharma04 opened this issue Apr 2, 2024 · 1 comment

Comments

@DeepakSharma04
Copy link

Version

29.6.3

Steps to reproduce

My js file

import React, { Component } from "react";
import {
  Text,
  View,
  TextInput,
  Keyboard,
  Platform,
  BackHandler,
  Modal,
  TouchableOpacity
} from "react-native";
import Icon from "react-native-vector-icons/FontAwesome5";
import { Button, ActivityIndicator } from "react-native-paper";
import AppRoutes from "../../../AppRoutes";

import AsyncStorage from "@react-native-community/async-storage";
import stringsoflanguages from "../../LanguageFile/CallLangConnection/MainLangConnection";
import Exstyles from "../../StyleSheet/EmailVerifyCss/VerifyEmailcss";
import fetchNetworkError from "../../NetworkError/NetworkError";
import FontFamily from "../../../constants/FontFamily";
import COLORS from "../../../constants/Colors";
import Images from "../../../constants/Images";
import axios from "@customAxios";
import showFlashMessage from '../../../util/FlashMessageComponent';

export default class VerifyEmail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      InActiveEmail: "",
      responseMessage: "",
      url: "",
    };
  }
  componentDidMount = () => {
    AsyncStorage.getItem("url").then((value) => this.setState({ url: value }));
    AsyncStorage.getItem("InActiveEmail").then((value) => {
      if (value != null) {
        this.setState({ InActiveEmail: value });
      }
    });
    BackHandler.addEventListener(
      "hardwareBackPress",
      this.handleBackButtonClick
    );
  };
  /* go back for android start*/
  handleBackButtonClick = () => {
    this.props.navigation.navigate(AppRoutes.LOGINUSER);
    return true;
  };
  /* go back for android end*/
  /* go back for both the platefrom start*/
  goBack = () => {
    this.props.navigation.navigate(AppRoutes.LOGINUSER);
    return true;
  };
  /* go back for both the platefrom end*/
  /* update email form server start*/
  resendActiveLink = () => {
    this.setState({ isSendClicked: true });
    const SendBody = {
      email: this.state.InActiveEmail,
    };
    axios.post("/v3/api/send-email-verification-link", SendBody)
      .then((responseData) => {
        this.setState({ isSendClicked: false });
        this.setState({ responseMessage: responseData.data.message });
        if (this.state.responseMessage) {
          showFlashMessage(responseData.data.message,'success',4000);

          this.props.navigation.navigate(AppRoutes.LOGINUSER);
          this.setState({ isSendClicked: false });
        }
      })
      .catch((error) => {
        this.setState({ isSendClicked: false });
        const ErrorResponseData = {
          ErrorResponse: error,
        };
        fetchNetworkError(ErrorResponseData)
          .then((res) => {
            if (res === "API is currently disabled.") {
              showFlashMessage(res,'info',2000);

              AsyncStorage.clear();
              AsyncStorage.setItem("url", this.state.url);
              this.props.navigation.navigate(AppRoutes.LOGINURL);
            } else {
              showFlashMessage(res,'info',2000);

            }
          })
          .catch((err) => { });
      });
  };
  /* update email form server end*/
  /* already update start */
  already = () => {
    Keyboard.dismiss();
    this.props.navigation.navigate(AppRoutes.UPDATEDEMAIL);
    return true;
  };
  /* already update end */
  componentWillUnmount = () => {
    BackHandler.removeEventListener(
      "hardwareBackPress",
      this.handleBackButtonClick
    );
  };
  render() {
    return this.state.InActiveEmail == 0 ? (
      <View style={Exstyles.container}>
        <ActivityIndicator size={30} color={COLORS.primary} style={{ alignSelf: 'center', flex: 1 }} />
      </View>
    ) : (
      <View style={Exstyles.container}>
        <View style={{ marginTop: Platform.OS === 'ios' ? 45 : 25 }}>
          <Icon
            name="arrow-left"
            style={{ padding: 20 }}
            size={18}
            onPress={this.goBack}
          />
          <View style={Exstyles.mainContainer}>
            <Text style={Exstyles.title}>
              {stringsoflanguages.VERIFYCONTAINONE}{" "}
            </Text>

            <Text style={Exstyles.textOne}>
              {stringsoflanguages.VERIFYCONTAINTWO} {this.state.InActiveEmail}
              {stringsoflanguages.VERIFYCONTAINTHREE}
            </Text>
            {this.state.isSendClicked ? (
              <ActivityIndicator size={30} color={COLORS.primary} />
            ) : (
              <TouchableOpacity
                style={Exstyles.buttom}
                onPress={this.resendActiveLink}
              >
                <Text style={Exstyles.text}>
                  {stringsoflanguages.RESENDLINK}{" "}
                </Text>
              </TouchableOpacity>
            )}
            <Text style={Exstyles.textTwo}>{stringsoflanguages.VERIFYOR} </Text>
            <TouchableOpacity
              style={Exstyles.buttom}
              onPress={this.already}
            >
              <Text style={Exstyles.text}>
                {stringsoflanguages.VERIFYEMAILUPDATE}{" "}
              </Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  }
}

test file

import React from 'react';
import VerifyEmail from '../../src/components/functionality/VerifyEmail/VerifyEmail';
import renderer from 'react-test-renderer';
import moxios from 'moxios';
import { ApiDisabled } from '../../src/UnitTestCaseResponse/moxiosRequestResponses';
import { VerifyEmailResponse } from '../../src/UnitTestCaseResponse/UnitTestCaseResponse/VerifyEmail/moxiosRequestResponses';
import AppRoutes from "../../src/AppRoutes";


const createTestProps = props => ({
    navigation: {
        navigate: jest.fn(),
        state: jest.fn(),
    },
    ...props,
});

describe('VerifyEmail Screen component Unit Testing', () => {
    beforeEach(() => {
        moxios.install();
    });

    afterEach(() => {
        moxios.uninstall();
    });
    props = createTestProps({});

    it('handleBackButtonClick method', (done) => {
        const component = renderer.create(<VerifyEmail {...props} />).getInstance();
        component.handleBackButtonClick();
        setTimeout(() => {
            expect(component.handleBackButtonClick()).toBe(true);
            expect(props.navigation.navigate).toHaveBeenCalledWith(AppRoutes.LOGINUSER);
            done();
        }, 1);
    });

    it('goBack method', (done) => {
        const component = renderer.create(<VerifyEmail {...props} />).getInstance();
        component.goBack();
        setTimeout(() => {
            expect(component.goBack()).toBe(true);
            expect(props.navigation.navigate).toHaveBeenCalledWith(AppRoutes.LOGINUSER);
            done();
        }, 1);
    });

    it('user pass email', (done) => {
        const component = renderer.create(<VerifyEmail {...props} />).getInstance();

        component.state.isSendClicked = true;
        component.state.InActiveEmail = 'h@demo.com';

        moxios.stubRequest('/v3/api/send-email-verification-link', {
            status: 200,
            response: VerifyEmailResponse,
        });
        component.resendActiveLink();

        setTimeout(() => {
            expect(component.state.isSendClicked).toBe(false);
            expect(component.state.responseMessage).toEqual(
                VerifyEmailResponse.message
            );

            expect(moxios.requests.mostRecent().url).toBe(
                '/v3/api/send-email-verification-link',
            );
            done();
        }, 1);
    });

    it('when the network is not working then catch the responces error ', (done) => {
        const component = renderer.create(<VerifyEmail {...props} />).getInstance();
        component.state.isSendClicked = true;
        component.state.InActiveEmail = 'h@demo.com';
        moxios.stubRequest('/v3/api/send-email-verification-link', {
            status: 400,
            response: { Error: 'Network Error' },
        });
        component.resendActiveLink();
        setTimeout(() => {
            expect(component.state.isSendClicked).toBe(false);
            expect(component.state.responseMessage).toEqual('');
            expect(moxios.requests.mostRecent().url).toBe(
                '/v3/api/send-email-verification-link',
            );
            done();
        }, 1);
    });

    it('user pass right and real input value,but api is Disabled ', (done) => {
        const component = renderer.create(<VerifyEmail {...props} />).getInstance();
        component.state.isSendClicked = true;
        component.state.InActiveEmail = 'h@demo.com';
        moxios.stubRequest('/v3/api/send-email-verification-link', {
            status: 400,
            response: ApiDisabled,
        });
        component.resendActiveLink();
        setTimeout(() => {
            expect(component.state.isSendClicked).toBe(false);
            expect(component.state.responseMessage).toEqual('');
            expect(moxios.requests.mostRecent().url).toBe(
                '/v3/api/send-email-verification-link',
            );
            done();
        }, 1);
    });

    it('already method', (done) => {
        const component = renderer.create(<VerifyEmail {...props} />).getInstance();
        component.already();
        setTimeout(() => {
            expect(component.already()).toBe(true);
            expect(props.navigation.navigate).toHaveBeenCalledWith(AppRoutes.UPDATEDEMAIL);
            done();
        }, 1);
    });
});

Expected behavior

It should be pass but fail.

Actual behavior

/Users/deepaksharma/Desktop/Agent-Upgrade/faveo-helpdesk-react-native/node_modules/flow-parser/flow_parser.js:818
throw a}function
^

JestAssertionError: expect(received).toEqual(expected) // deep equality

Expected: "We have sent an activation link to h@demo.c***. Please check your mailbox and click on the link to activate your account then try again."
Received: ""
    at Timeout.toEqual [as _onTimeout] (/Users/deepaksharma/Desktop/Agent-Upgrade/faveo-helpdesk-react-native/__tests__/VerifyEmail/VerifyEmail.test.js:62:53)
    at listOnTimeout (node:internal/timers:569:17)
    at processTimers (node:internal/timers:512:7) {
  matcherResult: {
    actual: '',
    expected: 'We have sent an activation link to h@demo.c***. Please check your mailbox and click on the link to activate your account then try again.',
    message: '\x1B[2mexpect(\x1B[22m\x1B[31mreceived\x1B[39m\x1B[2m).\x1B[22mtoEqual\x1B[2m(\x1B[22m\x1B[32mexpected\x1B[39m\x1B[2m) // deep equality\x1B[22m\n' +
      '\n' +
      'Expected: \x1B[32m"We have sent an activation link to h@demo.c***. Please check your mailbox and click on the link to activate your account then try again."\x1B[39m\n' +
      'Received: \x1B[31m""\x1B[39m',
    name: 'toEqual',
    pass: false
  }
}

Node.js v18.19.0
error Command failed with exit code 7.

Additional context

I'm using "moxios": "^0.4.0", for mocking api call and "babel-plugin-module-resolver": "^5.0.0" for axios config like

axiosconfig.js

import axios from "axios";
import AsyncStorage from "@react-native-community/async-storage";

// Set config defaults when creating the instance
const axiosInstance = axios.create();
axiosInstance.interceptors.request.use(async function (config) {
  const Token = await AsyncStorage.getItem('token');
  config.baseURL = await AsyncStorage.getItem('url');
  config.headers['Authorization'] = Token ? 'Bearer ' + Token : '';
  return config;
});

export default axiosInstance;

.babelrc


{
    "plugins": [
      ["module-resolver", {
        "root": ["./src"],
        "alias": {
          "@customAxios": "./src/axiosConfig"
        }
      }]
    ]
  }

Environment

System:
    OS: macOS 14.3.1
    CPU: (8) arm64 Apple M1
  Binaries:
    Node: 18.19.0 - /opt/homebrew/bin/node
    Yarn: 1.22.17 - /opt/homebrew/bin/yarn
    npm: 10.2.3 - /opt/homebrew/bin/npm
  npmPackages:
    jest: ^29.6.3 => 29.7.0
Copy link

github-actions bot commented May 2, 2024

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 30 days.

@github-actions github-actions bot added the Stale label May 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant