RTK Query Error: 'AbortError: Aborted' while running test

Viewed 29

I'm trying to run a test on login form submit which goes through a Rest API call to authenticate a user.

I have configured MSW for mocking the rest API. Whenever I am running the npm test command the rest api call isn't going through and returning an error. Seems like the mock API isn't working in this case

I have configured MSW for mocking the rest API. I am attaching the handler file, jest setup file and screen file below for reference.

jest.setup.config

import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock';
import 'whatwg-fetch';


global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

jest.mock('@react-native-async-storage/async-storage', () => mockAsyncStorage);

login.screen.tsx

import React from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { Button, Pressable, SafeAreaView, Text, View } from 'react-native';

import styles from './EmailLogin.style';
import Input from '../../components/Input/Input.component';
import { color } from '../../theme';
import LinearGradient from 'react-native-linear-gradient';
import { setUser } from '../../stores/user.reducer';
import { useLoginUserMutation } from '../../services/api/auth';
import { useAppDispatch } from '../../hooks/redux';

const EMAIL_PATTERN = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;

interface IEmailFormInputs {
  email: string;
  password: string;
}

const EmailLogin: React.FC = ({ navigation }: any) => {
  const dispatch = useAppDispatch();

  const [loginUser, { isLoading, isError, error, isSuccess }] =
    useLoginUserMutation();

  const onSubmit: SubmitHandler<IEmailFormInputs> = async requestData => {
    try {
      const { result } = await loginUser(requestData).unwrap();
      dispatch(setUser(result));
      navigation.navigate('Home');
    } catch (err) {
      console.log(err);
    }
  };

  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<IEmailFormInputs>({
    mode: 'onChange',
    defaultValues: {
      email: '',
      password: '',
    },
  });

  return (
    <SafeAreaView style={styles.whiteBackground}>
      <View style={styles.mainContainer}>
        <View style={styles.welcomeTextContainer}>
          <Text style={styles.welcomeTextTitle}>HELLO,</Text>
          <Text style={styles.welcomeTextSubTitle}>Welcome back</Text>
        </View>
        <View style={styles.inputContainer}>
          <Input
            name="email"
            control={control}
            rules={{
              pattern: {
                value: EMAIL_PATTERN,
                message: 'Invalid email address',
              },
            }}
            error={errors.email}
            placeholder={'Email'}
            autoCapitalize={'none'}
            autoCorrect={false}
          />
        </View>
        <View style={styles.inputContainer}>
          <Input
            name="password"
            control={control}
            rules={{
              minLength: {
                value: 3,
                message: 'Password should be minimum 3 characters long',
              },
            }}
            secureTextEntry={true}
            error={errors.password}
            placeholder={'Password'}
            autoCapitalize={'none'}
            autoCorrect={false}
          />
        </View>
        <Pressable onPress={handleSubmit(onSubmit)}>
          <LinearGradient
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 0 }}
            colors={color.gradient.primary}
            style={styles.buttonContainer}>
            <Text style={styles.buttonText}>Login</Text>
          </LinearGradient>
        </Pressable>
      </View>
    </SafeAreaView>
  );
};

export default EmailLogin;

login.spec.js

import React from 'react';
import { render, screen, fireEvent, waitFor, act } from '../../test-utils';
import { server } from '../../mocks/server';
import EmailLogin from './EmailLogin.screen';

describe('Home', () => {
  //handles valid input submission
  it('handle valid form submission', async () => {
    await render(<EmailLogin />);

    await act(async () => {
      fireEvent(
        screen.getByPlaceholderText('Email'),
        'onChangeText',
        'sample@email.com',
      );
      fireEvent(
        screen.getByPlaceholderText('Password'),
        'onChangeText',
        'password',
      );
      fireEvent.press(screen.getByText('Login'));
    
      //expected result on success login to be mentioned here
    });
  });
});

mocks/handler.js

import { rest } from 'msw';
import config from '../config';

export const handlers = [
  rest.post(`*url*/user/auth`, (req, res, ctx) => {
    console.log(req);
    // successful response
    return res(
      ctx.status(200),
      ctx.json({
        success: true,
        result: {
          auth_token: ['authtoken'],
          email: req.bodyUsed.email,
          id: 1,
          first_name: 'xxx',
          last_name: 'xxx',
          number: 'xxxxxxx',
          user_state: 1,
          phone_verified: true,
        },
      }),
    );
  }),
];

I get the following error when

console.log
      { status: 'FETCH_ERROR', error: 'AbortError: Aborted' }

      at src/screens/EmailLogin/EmailLogin.screen.tsx:32:15
          at Generator.throw (<anonymous>)
0 Answers
Related