Search code examples
javascriptfirebasejestjsstripe-payments

My jest file isn't using the correct return


I'm pretty sure that it will be something easy to fix, but I've been stucked with this for a while. I'm building a background (back-end) test file using Jest. Here's my background.test.js `

const fileConnection = require('../background');
const firebaseConnection = require('../background');
const stripeConnection = require('../background');

test('File Test', () => {
  expect(fileConnection).toBe(true);
});

describe('Background Test', () => {
  test('Firebase connection', async () => {
    expect(firebaseConnection).not.toBe(null);
  });
  test('Stripe and Back-End connection', async () => {
    expect(stripeConnection).not.toBe(null);
  });
});

`

And my background.js file:

import { db } from 'firebase/firestore';

let test = false;

/**
 *
 */
function fileConnection() {
  test = true;
  return test;
}

/**
 *
 */
function firebaseConnection() {
  try {
    return db;
  } catch (error) {
    return null;
  }
}

/**
 *
 */
function stripeConnection() {
  // the backend stripe connection is on CENSORED
  // So I need to check if the connection is working
  try {
    fetch('CENSORED');
    return 'Stripe connection is working';
  } catch (error) {
    return null;
  }
}

module.exports = (fileConnection, firebaseConnection, stripeConnection);

Now, the error I'm getting is this one:

 ✕ File Test (4 ms)
  Background Test
    ✓ Firebase connection (1 ms)
    ✓ Stripe and Back-End connection (1 ms)

  ● File Test

    expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: [Function stripeConnection]

       7 |
       8 | test('File Test', () => {
    >  9 |   expect(fileConnection).toBe(true);
         |                          ^
      10 | });
      11 |
      12 | describe('Background Test', () => {

      at Object.toBe (src/test/background.test.js:9:26)

As you can see, I'm getting the response of the stripe connection on the file test function. I believe that it can have something to do with the way I'm exporting my .js file. Thanks for helping me!

I've tried changing the way I use the exports, and I'm not sure why the connection with firebase isn't dropping that error. Only the stripe connection does. I've tried copying the code style but it won't work.


Solution

  • The syntax for your module.exports statement is wrong, but I assume it was correct when you ran the tests. Just to be sure: you have to use curly braces.

    module.exports = {fileConnection, firebaseConnection, stripeConnection};
    

    As for the test failure:
    Jest is telling you (correctly) that fileConnection has the value [Function stripeConnection], because it is a function. Your intention was comparing the result of that function so you have to call it. Instead of expect(fileConnection).toBe(true) you need expect(fileConnection()).toBe(true) (note the function invokation).