Cross origin http://localhost forbidden error when testing async services with Create React App and Jest

Viewed 890

Trying to test my services but getting Cross origin http://localhost forbidden error. I'm not sure if it has to do with my authHeader which I'm not passing down. Should I be passing my JWT token down with the test? when I console log the service and run the test I can see that my token is present.

Here is my test

import React from 'react'
import { userService } from './user-service'

let user

beforeAll(async() => {
  const credentials = {
    email: 'example@example.com',
    password: 'somepassword'
  }

  user = await userService.login(credentials)
})

test('check res after login', async() => {
  expect(user.name).toBe('example')
  expect(user.token).toBeDefined()
})

test('get user profile', async() => {
  const userProfile = await userService.getProfile()
  console.log('profile')

  expect(userProfile.name).toBeDefined()
  expect(userProfile.language).toBeDefined()
})

test('create a new user', async() => {
  const userBody = {
    confirmPassword: "password",
    email: "test@iamtesting.com",
    name: "test",
    password: "password",
    phone: "999",
    roleName: "default",
  }

  const createUser = await userService.create(userBody)

  expect(createUser.name).toBe('test')
  expect(createUser.phone).toBe('999')
})

and my service code

function login(credentials) {
  const requestOptions = {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(credentials)
  };

  return fetch(`${process.env.REACT_APP_API}/login`, requestOptions)
    .then(handleResponse)
    .then(user => {
      // login successful if there's a jwt token in the response
      if (user.token) {
        // store user details and jwt token in local storage to keep user logged in between page refrehes
          localStorage.setItem('user', JSON.stringify(user));
      }

      return user;
    });
}
function getProfile() {
  const requestOptions = {
    method: 'GET',
    headers: authHeader()
  }

  return fetch(`${getBackend()}/user?profile=true`, requestOptions).then(handleResponse); 
}

function create(user) {
  const requestOptions = {
    method: 'POST',
    headers: authHeader(),
    body: JSON.stringify(user)
  }

  return fetch(`${getBackend()}/user`, requestOptions).then(handleResponse); 
}
0 Answers
Related