#StackBounty: #javascript #reactjs #jestjs #react-testing-library #react-error-boundary How do I test the fallback component for the Er…

Bounty: 100

I have this component:

import React, { lazy, Suspense } from 'react';
import { ErrorBoundary } from '../ErrorBoundary';

const FALLBACK = <svg aria-label="" data-testid="icon-fallback" viewBox="0 0 21 21" />;

const ERROR = (
    <svg data-testid="icon-notdef" viewBox="0 0 21 21">
        <path d="M0.5,0.5v20h20v-20H0.5z M9.1,10.5l-6.6,6.6V3.9L9.1,10.5z M3.9,2.5h13.2l-6.6,6.6L3.9,2.5z M10.5,11.9l6.6,6.6H3.9 L10.5,11.9z M11.9,10.5l6.6-6.6v13.2L11.9,10.5z" />
    </svg>
);

export const Icon = ({ ariaLabel, ariaHidden, name, size }) => {
    const LazyIcon = lazy(() => import(`../../assets/icons/${size}/${name}.svg`));
    return (
        <i aria-hidden={ ariaHidden }>
            <ErrorBoundary fallback={ ERROR }>
                <Suspense fallback={ FALLBACK }>
                    <LazyIcon aria-label={ ariaLabel } data-testid="icon-module" />
                </Suspense>
            </ErrorBoundary>
        </i>
    );
};

I’m trying to test the condition where an SVG is passed in that doesn’t exist, in turn rendering the <ErrorBoundary /> fallback. The ErrorBoundary works in the browser, but not in my test.

This is the failing test:

test('shows notdef icon', async () => {
    const { getByTestId } = render(<Icon name='doesnt-exist' />);
    const iconModule = await waitFor(() => getByTestId('icon-notdef'));
    expect(iconModule).toBeInTheDocument();
});

I get this error message:

TestingLibraryElementError: Unable to find an element by: [data-testid="icon-notdef"]”.

How do I access ErrorBoundary fallback UI in my test?

Edit

This is the code for the <ErrorBoundary /> component:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export class ErrorBoundary extends Component {
    constructor(props) {
        super(props);
        this.state = {
            error: '',
            errorInfo: '',
            hasError: false,
        };
    }

    static getDerivedStateFromError(error) {
        return { hasError: true, error };
    }

    componentDidCatch(error, errorInfo) {
        console.error({ error, errorInfo });
        this.setState({ error, errorInfo });
    }

    render() {
        const { children, fallback } = this.props;
        const { error, errorInfo, hasError } = this.state;

        // If there is an error AND a fallback UI is passed in…
        if (hasError && fallback) {
            return fallback;
        }

        // Otherwise if there is an error with no fallback UI…
        if (hasError) {
            return (
                <details className="error-details">
                    <summary>There was an error.</summary>
                    <p style={ { margin: '12px 0 0' } }>{error && error.message}</p>
                    <pre>
                        <code>
                            {errorInfo && errorInfo.componentStack.toString()}
                        </code>
                    </pre>
                </details>
            );
        }

        // Finally, render the children.
        return children;
    }
}

ErrorBoundary.propTypes = {
    children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired,
    fallback: PropTypes.node,
};

… and this is the full error with DOM that I get for the test:

shows notdef icon

    TestingLibraryElementError: Unable to find an element by: [data-testid="icon-notdef"]

    <body>
      <div>
        <i
          aria-hidden="false"
          class="Icon Icon--sm"
        >
          <span
            aria-label=""
            data-testid="icon-module"
          />
        </i>
      </div>
    </body>

    <html>
      <head />
      <body>
        <div>
          <i
            aria-hidden="false"
            class="Icon Icon--sm"
          >
            <span
              aria-label=""
              data-testid="icon-module"
            />
          </i>
        </div>
      </body>
    </html>Error: Unable to find an element by: [data-testid="icon-notdef"]

Lastly, my SVG mock:

import React from 'react';

const SvgrMock = React.forwardRef(
    function mySVG(props, ref) {
        return <span { ...props } ref={ ref } />;
    },
);

export const ReactComponent = SvgrMock;
export default SvgrMock;


Get this bounty!!!

#StackBounty: #javascript #jestjs #axios How do I get response data out of the axios mock file and into the test?

Bounty: 100

I’m having trouble with the placement of my response data for an axios mock. If I include the data in the mock file, the test passes. If I include it in the test with axiosMock.get.mockResolvedValue(); it doesn’t. I don’t want the response in the mock file because that file needs to work with all axios tests.

If I include my response in the axios mock file like this, things work as expected.

// __mocks__/axios.js
export default {
  create: jest.fn(() => ({
    get: jest.fn().mockResolvedValue({
      data: {
        data: [
          {
            label: 'Started',
            value: 'started',
            type: 'Milestone',
          },
          {
            label: 'Detected',
            value: 'detected',
            type: 'Milestone',
          },
          {
            label: 'Acknowledged',
            value: 'acknowledged',
            type: 'Milestone',
          },
        ],
      },
    }),
    interceptors: {
      request: { use: jest.fn(), eject: jest.fn() },
      response: { use: jest.fn(), eject: jest.fn() },
    },
  })),
  get: jest.fn(),
};

My test file:

// Condition.spec.js
test('fetches and displays data', async () => {
  axiosMock.get.mockResolvedValue();

  const { container } = render(
    <Condition {...props} />
  );
  await wait(() => expect(container.textContent).toContain('Current milestone is Acknowledged'));
  expect(container).toBeDefined();
});

If I remove it from the mock file and place it in the test, it fails:

// __mocks__/axios.js
export default {
  create: jest.fn(() => ({
    get: jest.fn().mockResolvedValue(),
    interceptors: {
      request: { use: jest.fn(), eject: jest.fn() },
      response: { use: jest.fn(), eject: jest.fn() },
    },
  })),
  get: jest.fn(),
};
// Condition.spec.js
test('fetches and displays data', async () => {
  axiosMock.get.mockResolvedValue({
    data: {
      data: [
        {
          label: 'Started',
          value: 'started',
          type: 'Milestone',
        },
        {
          label: 'Detected',
          value: 'detected',
          type: 'Milestone',
        },
        {
          label: 'Acknowledged',
          value: 'acknowledged',
          type: 'Milestone',
        },
      ],
    },
  });

  const { container } = render(
    <Condition {...props} />
  );
  await wait(() => expect(container.textContent).toContain('Current milestone is Acknowledged'));
  expect(container).toBeDefined();
});

How do I get my response data out of the mock file and into the test itself?


Get this bounty!!!

#StackBounty: #angular #unit-testing #angular-material #mocking #jestjs Angular Jest Testing a component that opens a MatDialog – open …

Bounty: 100

Similar to this question, but it doesn’t provide an answer that works for me.

I have a simple component that has a method that opens a dialog:

  enterGiveaway() {
    this.dialog.open(SpendTicketsDialogComponent, {
      width: '370px',
      height: '600px'
    });
  }

For now I just want to test that calling that method results in the dialog being opened.

The test fails with this error:

  expect(spy).toBeCalledTimes(expected)

    Expected number of calls: 1
    Received number of calls: 0

with this code:

    import {async, ComponentFixture, TestBed} from '@angular/core/testing';
    
    import {GiveawayItemComponent} from './giveaway-item.component';
    import {giveawaysMock} from '../../../../../mocks/giveaways.mock';
    import {MaterialModule} from '../../material.module';
    import {getTranslocoModule} from '../../../transloco-testing.module';
    import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
    import {MatDialog} from '@angular/material/dialog';
    import {EMPTY} from 'rxjs';
    import {SpendTicketsDialogComponent} from '../dialogs/tickets-dialog/spend-tickets-dialog.component';
    import {NumberFormatter} from '../../filters/numberFormatter/numberFormatter.filter';
    import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
    import {BrowserModule} from '@angular/platform-browser';
    
    describe('GiveawayItemComponent', () => {
      let component: GiveawayItemComponent;
      let fixture: ComponentFixture<GiveawayItemComponent>;
      let dialog: any;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [
            GiveawayItemComponent,
            SpendTicketsDialogComponent,
            NumberFormatter
          ],
          imports: [
            MaterialModule,
            BrowserAnimationsModule,
            getTranslocoModule({})
          ],
          schemas: [CUSTOM_ELEMENTS_SCHEMA]
        })
          .overrideModule(BrowserModule, {
            set: {entryComponents: [SpendTicketsDialogComponent]}
          })
          .compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(GiveawayItemComponent);
        component = fixture.componentInstance;
        component.giveaway = giveawaysMock[0];
        component.numberOfChances = 100;
        dialog = TestBed.inject(MatDialog);
        fixture.detectChanges();
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    
      describe('enterGiveaway', () => {
        it('should open the spend tickets dialog', async(() => {
          component.enterGiveaway();
          fixture.detectChanges();
          const spy = spyOn(dialog, 'open').and.returnValue({
            afterClosed: () => EMPTY
          });
    
          expect(spy).toBeCalledTimes(1);
        }));
      });
    });

I understand of course, that MatDialog is not referencing the actual SpendTicketsDialogComponent which is the one that is opened. So I tried providing a mock object for the dialog:

    import {async, ComponentFixture, TestBed} from '@angular/core/testing';
    
    import {GiveawayItemComponent} from './giveaway-item.component';
    import {giveawaysMock} from '../../../../../mocks/giveaways.mock';
    import {MaterialModule} from '../../material.module';
    import {getTranslocoModule} from '../../../transloco-testing.module';
    import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
    import {MatDialog} from '@angular/material/dialog';
    import {of} from 'rxjs';
    import {SpendTicketsDialogComponent} from '../dialogs/tickets-dialog/spend-tickets-dialog.component';
    import {NumberFormatter} from '../../filters/numberFormatter/numberFormatter.filter';
    import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
    import {BrowserModule} from '@angular/platform-browser';
    
    class dialogMock {
      open() {
        return {
          afterClosed: () => of({})
        };
      }
    }
    
    describe('GiveawayItemComponent', () => {
      let component: GiveawayItemComponent;
      let fixture: ComponentFixture<GiveawayItemComponent>;
      let dialog: any;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [
            GiveawayItemComponent,
            SpendTicketsDialogComponent,
            NumberFormatter
          ],
          imports: [
            MaterialModule,
            BrowserAnimationsModule,
            getTranslocoModule({})
          ],
          providers: [{provide: MatDialog, useValue: dialogMock}],
          schemas: [CUSTOM_ELEMENTS_SCHEMA]
        })
          .overrideModule(BrowserModule, {
            set: {entryComponents: [SpendTicketsDialogComponent]}
          })
          .compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(GiveawayItemComponent);
        component = fixture.componentInstance;
        component.giveaway = giveawaysMock[0];
        component.numberOfChances = 100;
        dialog = TestBed.inject(MatDialog);
        fixture.detectChanges();
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    
      describe('enterGiveaway', () => {
        it('should open the spend tickets dialog', async(() => {
          component.enterGiveaway();
          fixture.detectChanges();
          const spy = spyOn(dialog, 'open').and.callThrough();
    
          expect(spy).toBeCalledTimes(1);
        }));
      });
    });

but this throws the error this.dialog.open is not a function.

I actually don’t think either solution is correct, because I need to check that calling enterGiveaway opens the SpendTicketsDialog.

So how can I verify that?


Get this bounty!!!

#StackBounty: #angular #asynchronous #testing #jestjs Angular Jest async test seems to overflow results from one test to another

Bounty: 100

In Angular, using Jest we have 2 tests that test a method on a component class:

  describe('checkEmailStatus', () => {
    it('set VERIFIED page design when email verification succeeds', async () => {
      jest.spyOn(authService, 'checkEmailVerification');
      await expect(component.checkEmailStatus()).resolves.toEqual(undefined);
      expect(authService.checkEmailVerification).toBeCalledTimes(1);
      expect(component.pageDesign.key).toBe('verified');
    });

    it('set ERROR page design when email verification fails', async () => {
      const checkEmail = jest.spyOn(authService, 'checkEmailVerification');
      checkEmail.mockImplementation(() => {
        return Promise.reject(false);
      });
      await expect(component.checkEmailStatus()).resolves.toEqual(undefined);
      expect(authService.checkEmailVerification).toBeCalledTimes(1);
      expect(component.pageDesign.key).toBe('error');
    });
  });

These tests have been running fine for a month. Nothing about this component has changed and neither have we changed Jest version (25.2.7) yet now the 2nd test complains that the method was called 3 times.

If I comment out the first test, the 2nd tests passes.

It seems that the first test is not tearing down correctly – is there something I need to do to force that? (I tried using the done() callback, but it made no difference)

UPDATE

This is the method under test:

  async checkEmailStatus(): Promise<void> {
    this.isLoading = true;
    try {
      await this.authService.checkEmailVerification('');
      this.setPageDesign('verified');
      this.isLoading = false;
    } catch (error) {
      this.setPageDesign('error');
      this.isLoading = false;
    }
  }

This is the stubbed authService:

import {Observable, BehaviorSubject, of} from 'rxjs';
import {switchMap} from 'rxjs/operators';
import {mockUsers} from '../../../../mocks/user.mock';

// tslint:disable-next-line: completed-docs
function initStub() {
  const userId$ = new BehaviorSubject<string>(null);

  return {
    userId$,
    checkEmailVerification(): Promise<boolean> {
      return Promise.resolve(true);
    }
  };
}

export const authServiceStub = initStub();

UPDATE 2

This is the complete test file:

import {AuthService} from 'src/app/shared/services/auth.service';
import {async, ComponentFixture, TestBed} from '@angular/core/testing';

import {VerifyEmailComponent} from './verify-email.component';
import {SharedModule} from '../shared/shared.module';
import {getTranslocoModule} from '../transloco-testing.module';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {AngularFireModule} from '@angular/fire';
import {environment} from 'src/environments/environment';
import {routerStub} from '../test/helpers/router.stub';
import {authServiceStub} from '../test/helpers/auth.service.stub';

fdescribe('VerifyEmailComponent', () => {
  let component: VerifyEmailComponent;
  let fixture: ComponentFixture<VerifyEmailComponent>;
  let authService: AuthService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [VerifyEmailComponent],
      imports: [
        SharedModule,
        getTranslocoModule({}),
        BrowserAnimationsModule,
        AngularFireModule.initializeApp(environment.firebase)
      ],
      providers: [routerStub, {provide: AuthService, useValue: authServiceStub}]
    }).compileComponents();
    authService = TestBed.inject(AuthService);
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(VerifyEmailComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  describe('setPageDesign', () => {
    it('should set the correct design for VERIFY', () => {
      component.setPageDesign('verify');
      expect(component.pageDesign.key).toBe('verify');
    });

    it('should set the correct design for VERIFIED', () => {
      component.setPageDesign('verified');
      expect(component.pageDesign.key).toBe('verified');
    });

    it('should set the correct design for ERROR', () => {
      component.setPageDesign('error');
      expect(component.pageDesign.key).toBe('error');
    });

    it('should set the ERROR design for unknown status values', () => {
      component.setPageDesign('');
      expect(component.pageDesign.key).toBe('error');
    });
  });

  describe('checkEmailStatus', () => {
    it('set VERIFIED page design when email verification succeeds', async () => {
      jest.spyOn(authService, 'checkEmailVerification');
      await expect(component.checkEmailStatus()).resolves.toEqual(undefined);
      expect(authService.checkEmailVerification).toBeCalledTimes(1);
      expect(component.pageDesign.key).toBe('verified');
    });

    it('set ERROR page design when email verification fails', async () => {
      const checkEmail = jest.spyOn(authService, 'checkEmailVerification');
      checkEmail.mockImplementation(() => {
        return Promise.reject(false);
      });
      await expect(component.checkEmailStatus()).resolves.toEqual(undefined);
      fixture.detectChanges();

      expect(authService.checkEmailVerification).toBeCalledTimes(1);
      expect(component.pageDesign.key).toBe('error');
    });
  });

  describe('onClickContinue', () => {
    // TODO: implement 2 tests for if/else cases of the button
    return undefined;
  });
});

This is the component code:

import {TranslocoService, TRANSLOCO_SCOPE} from '@ngneat/transloco';
import {Component, OnInit} from '@angular/core';
import {AuthService} from '../shared/services/auth.service';
import {Router} from '@angular/router';

// define static data to be used only by this component
interface PageDesign {
  icon: string;
  key: string;
}
const pageDesigns: PageDesign[] = [
  {
    icon: 'email-verified',
    key: 'verify'
  },
  {
    icon: 'email-verified',
    key: 'verified'
  },
  {
    icon: 'email-expired',
    key: 'error'
  }
];

@Component({
  selector: 'wn-verify-email',
  templateUrl: './verify-email.component.html',
  styleUrls: ['./verify-email.component.scss'],
  providers: [{provide: TRANSLOCO_SCOPE, useValue: 'verifyEmail'}]
})
export class VerifyEmailComponent implements OnInit {
  isLoading: boolean = false;
  pageDesign: PageDesign;

  constructor(
    public translocoService: TranslocoService,
    private authService: AuthService,
    private router: Router
  ) {}

  /**
   * Init
   */
  ngOnInit(): void {
    this.setPageDesign('verify');
    this.checkEmailStatus();
  }

  /**
   * Affects the current email data
   */
  setPageDesign(status: string): any {
    this.pageDesign = pageDesigns.find(
      emailDesign => emailDesign.key === status
    );
    if (!this.pageDesign)
      this.pageDesign = pageDesigns.find(
        emailDesign => emailDesign.key === 'error'
      );
  }

  /**
   * Check whether email address is verified
   */
  async checkEmailStatus(): Promise<void> {
    this.isLoading = true;
    try {
      await this.authService.checkEmailVerification('');
      this.setPageDesign('verified');
      this.isLoading = false;
    } catch (error) {
      this.setPageDesign('error');
      this.isLoading = false;
    }
  }

  /**
   * Click handler for the continue navigation button
   */
  onClickContinue(status: string) {
    if (status === 'verified')
      // TODO: use the continueURL from params and navigate to that
      console.error('continue url needed');
    else this.router.navigate(['/']);
  }
}


Get this bounty!!!

#StackBounty: #javascript #node.js #mocking #jestjs Jest method-invocation count is wrong?

Bounty: 50

Consider code –

// utils.js
export const foo = async (a, b) => {
   // do something
   bar(a)
}

export const bar = async (a) => {
   // do something
}

// utils.spec.js
const utils = require('./utils');

const barSpy = jest.spyOn(utils, 'bar');
const result = await utils.foo('a', 'b');

expect(barSpy).toHaveBeenCalledTimes(1);

The test is failing –

Error: expect(jest.fn()).toHaveBeenCalledTimes(expected)

Expected number of calls: 1
Received number of calls: 0

I read https://medium.com/@DavideRama/mock-spy-exported-functions-within-a-single-module-in-jest-cdf2b61af642 and https://github.com/facebook/jest/issues/936 but could not solve this with multiple permutations.

Do you see any issue with this?


Get this bounty!!!

#StackBounty: #javascript #node.js #unit-testing #jestjs Reseting node module in Jest

Bounty: 50

I have a Node.js app where index.js has different exports for Unix-like and Windows platforms.

import os from "os";

function throwNotSupportedError() {
  throw new Error("Platform not supported.");
}

console.log(os.platform());

switch (os.platform()) {
  case "darwin":
  case "linux":
    module.exports = {
      foo: require("./unix/foo"),
      bar: require("./unix/bar")
    };
    break;
  case "win32":
    module.exports = {
      foo: require("./win32/foo"),
      bar: require("./win32/bar")
    };
    break;
  default:
    throwNotSupportedError();
}

And I am trying to cover this file with unit tests which looks like this:

import os from "os";

jest.mock("os");

describe("Linux platform", () => {
  test("has `foo` and `bar` methods on Linux platform", () => {
    os.platform.mockImplementation(() => "linux");

    const app = require("../src");
    expect(app.foo).toBeTruthy();
    expect(app.bar).toBeTruthy();
  });
});

describe("Windows platform", () => {
  test("has `foo` and `bar` methods on Windows platform", () => {
    os.platform.mockImplementation(() => "win32");

    const app = require("../src");
    expect(app.foo).toBeTruthy();
    expect(app.bar).toBeTruthy();
  });
});

The thing is that os.platform.mockImplementation(() => "win32"); works but console.log(os.platform()); still shows linux even if I import the app in every test case const app = require("../src");.

Where is my mistake and how to solve it?


Get this bounty!!!

#StackBounty: #reactjs #typescript #react-native #jestjs #babel Error when running jest on a react native + typescript app (Jest encoun…

Bounty: 100

It seems like everyone and their mother are having a variation of this problem. Nothing worked from everything I have tried from all the SO questions and GH tickets.

It should actually be quite simple, since my project is pretty much a new barebone project. Yet I still can’t figure out what is wrong for the life of me.

When I run jest:

/Desktop/Dropbox/Programming/iphone-app/fe/App.spec.tsx:11
    const tree = react_test_renderer_1.default.create(<App_1.default />).toJSON();
                                                      ^

SyntaxError: Unexpected token <

My config files:

// jest.config.js

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

// tsconfig.json

{
    "compilerOptions": {
        "allowJs": false,
        "allowSyntheticDefaultImports": true,
        "noFallthroughCasesInSwitch": true,
        "experimentalDecorators": true,
        "esModuleInterop": true,
        "isolatedModules": true,
        "jsx": "react-native",
        "lib": [
            "es6"
        ],
        "moduleResolution": "node",
        "noEmit": true,
        "strict": true,
        "target": "esnext"
    },
    "exclude": [
        "node_modules"
    ]
}

// babel.config.js

module.exports = function (api) {
    api.cache(true);
    return {
        presets: ['babel-preset-expo'],
    };
};

EDIT #1

Just to be clear, I have tried using the react-native preset in the jest config file, with no success (same error):

// jest.config.js

module.exports = {
    preset: 'react-native',
    transform: {
        '^.+\.js$': '<rootDir>/node_modules/react-native/jest/preprocessor.js',
        '^.+\.tsx?$': 'ts-jest'
    },
    globals: {
        'ts-jest': {
            tsConfig: 'tsconfig.json'
        }
    },
    testEnvironment: 'node',
};


Get this bounty!!!

#StackBounty: #reactjs #jestjs #axios #enzyme #axios-mock-adapter Why my mock of my api return a 404 error?

Bounty: 100

I use axios-mock-adapter to mock my API, it works correctly but on one mock it returns a 404 error and I cannot found why.

There is here the sandbox with test, you can see when we run the test, the second check failed because the axios POST call haven’t be mock.

Mock of API (test part):

import axios from "axios";
import MockAdapter from 'axios-mock-adapter';
import Utils from "../Utils/Utils";

// Global variable for post request with axios
global.users_post = axios.create({
  baseURL: "http://localhost:5000/api/",
  headers: {'Content-Type': 'application/json'}
});

/* Mockup API */
var userMock = new MockAdapter(users_post);

const user_resp_full = {
  data: {
    first_name: "Test",
    last_name: "Test",
    email: "test@gmail.com",
    address: "Test",
    zipcode: 1010,
    city: "Test",
    admin: false
  }
}

const testAPI = () => {
    userMock
      .onPost("users", user_resp_full, Utils.getAuth())
      .reply(200, {data: {status: "success"}});
}

test("something", async () => {
  let tree = shallow(<UserManage type="create" uuid="" />);
  testAPI();
  await flushPromises();
  // Some test

  tree.find("#confirm-create").simulate("click");
  await flushPromises();
  // Error 404, mock isn't trigger
})

I have already check, data is the same, same for endpoint but it seems doesn’t mock it correctly.

Axios call in class:

function (fields) {
    users_post.post("users", fields, Utils.getAuth())
    .then(resp => {
      let data = resp.data;
      // Do something
    })
    .catch(resp => {
      let data = resp.response.data;
      // Display error
    });
}

At this point, in my Jest test it returns a 404 error, so it hasn’t mock my endpoint API (Other works).
The Utils.getAuth() function returns a header with a auth token.

Data send

That concerns content of data send (First is before the test call with mock, second is in the tested function and data log is the data send to api):

    console.log src/tests/UserManage.test.js:222
      POST USER 2
       {"first_name":"Test","last_name":"Test","email":"test@gmail.com","address":"Test","zipcode":1010,"city":"Test","admin":false}
    console.log src/Components/Users/UserManage.js:152
      POST USER
    console.log src/Components/Users/UserManage.js:153
       {"first_name":"Test","last_name":"Test","email":"test@gmail.com","address":"Test","zipcode":1010,"city":"Test","admin":false}

Update

This error happen only when I use a POST request with a header like that:

axios.post("http://localhost/api/user/update", {name: "Test"}, {headers: {"Authorization": "Bearer token")}});


Get this bounty!!!