Tips for testing and verifying the call to a specific Firebase method within a function using Jest

Within the file App.ts, I am utilizing the method

firebase.auth().signInWithEmailAndPassword(email, password)
.

Now, my objective is to conduct a unit test to ensure that when the

myAuthenticationPlugin.authenticate(email, password)
method is invoked from App.spec.ts, it triggers the
firebase.auth().signInWithEmailAndPassword(email, password)
method as this is the core functionality of App.ts.

Despite several attempts, I have been unable to find a solution.

App.ts

const App= {
    authenticate: async (email, password) => {
        await firebase.auth().signInWithEmailAndPassword(email, password)
  },
}

App.spec.ts

import myAuthenticationPlugin from 'authenticationPlugin/App'
import firebase from 'firebase/app'
jest.mock('firebase/app', () => {
  const firebase = {
    auth: jest.fn(() => {
      return {
        currentUser: {
          email: 'test',
          uid: '123',
          emailVerified: true
        },

        signInWithEmailAndPassword: jest.fn().mockImplementation()
      }
    }),
    initializeApp: jest.fn()
  }
  return firebase
})

describe('Test for authenticate ()', () => {
    it('signInWithEmailAndPassword ()', () => {
      const email = 'test'
      const password = 'mypassword'
      myAuthenticationPlugin.authenticate(email, password)
      expect(firebase.auth().signInWithEmailAndPassword).toHaveBeenCalled()
    })
  })

Error Received

● App.js (Authentication Plugin) › Test for authenticate () › signInWithEmailAndPassword ()

    expect(jest.fn()).toHaveBeenCalled()

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

      44 |       const password = 'mypassword'
      45 |       myAuthenticationPlugin.authenticate(email, password)
    > 46 |       expect(firebase.auth().signInWithEmailAndPassword).toHaveBeenCalled()
         |                                                          ^
      47 |     })
      48 |   })
      49 | })

      at Object.<anonymous> (tests/unit/App.spec.ts:46:58)

Answer №1

Below is the solution for the uni test:

app.ts:

import firebase from 'firebase/app';

const App = {
  authenticate: async (email, password) => {
    await firebase.auth().signInWithEmailAndPassword(email, password);
  },
};

export default App;

app.test.ts:

import App from './app';
import firebase from 'firebase/app';

jest.mock('firebase/app', () => {
  return {
    auth: jest.fn().mockReturnThis(),
    signInWithEmailAndPassword: jest.fn(),
  };
});

describe('61352544', () => {
  it('should pass', async () => {
    const email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b7aab3bfa2beb792b5bfb3bbbefcb1bdbf">[email protected]</a>';
    const password = '123';
    await App.authenticate(email, password);
    expect(firebase.auth().signInWithEmailAndPassword).toBeCalledWith(email, password);
  });
});

unit test results with coverage of 100%:

 PASS  stackoverflow/61352544/app.test.ts (12.122s)
  61352544
    ✓ should pass (9ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 app.ts   |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        14.061s

source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61352544

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Modify hyperlink attributes to enhance security and optimize user experience

$("a[href*='youtube']").attr('rel', 'prettyPhoto'); Having some trouble targeting links on a page containing "youtube" in the URL. I'm trying to set their rel attribute to "prettyPhoto" so they open in a lightbox window. ...

What steps can I take to resolve the CSP errors I am experiencing?

I am currently working with NextJs@12 and I am attempting to set up CSP for my application. Unfortunately, I keep encountering errors in my console and I cannot figure out where I am going wrong. Below is the current policy that I have in my next.config fi ...

Angular component injected with stub service is returning incorrect value

While attempting to write tests for my Angular component that utilizes a service, I encountered an issue. Despite initializing my userServiceStub property isLoggedIn with true, the UserService property appears false when running the tests. I experimented ...

Suggestions for a JavaScript tool that automatically crops images

Is there a tool available, either browser-based or in Java, that can analyze an uploaded image, identify different characters within it, and crop them out into separate images? For instance, if this image contains three unique runic symbols, I would like ...

The div is set to a position of absolute, causing the overflow-y property to be set to auto. As a

I am facing an issue with a div that has absolute positioning nested inside other divs. If you take a look at the code snippet below from http://jsfiddle.net/d8GYk/, you'll notice the styling properties applied to the div. <div style="position: ...

The message sent from the server via SocketIO seems to be malfunctioning

Currently, I am in the process of developing an application that utilizes websockets for facilitating server-client communication. The main idea behind this concept is to enable the client to request messages from the server, while also allowing the server ...

Error: Unable to locate the type definition file for the '@babel' package

I am currently working on a new project and here is the content of my package.json file. { "name": "dapp-boilerplate", "version": "1.0.0", "main": "index.js", "license": "MI ...

What could be causing my Express server to return a 404 error when trying to submit the form, all while failing to display any console

Having trouble setting up multi-user sessions similar to Google Docs, but my server file seems unresponsive. I've double-checked my fetch function and ensured it is accurate, yet no changes are occurring. Even console.logs from the server file command ...

How can we have a div stay at the top of the screen when scrolling down, but return to its original position when scrolling back up?

By utilizing this code, a div with position: absolute (top: 46px) on a page will become fixed to the top of the page (top: 0px) once the user scrolls to a certain point (the distance from the div to the top of the page). $(window).scroll(function (e) { ...

Ordering an array using Typescript within React's useEffect()

Currently, I am facing a TypeScript challenge with sorting an array of movie objects set in useEffect so that they are displayed alphabetically. While my ultimate goal is to implement various sorting functionalities based on different properties in the fut ...

The process of importing does not produce the anticipated System.register

I'm a beginner with Angular2, currently learning and practicing by doing exercises. I am enrolled in a Udemy course and comparing my exercise progress with the instructions provided. Here is a snippet from my app.component.ts file: import {Component ...

Updating content on a webpage via AJAX request without altering the original source code

Within the body of our document, referred to as "form.php," we have the following components: At the head section, there is a JavaScript code block: <script> function showUser(str) { if (str == "") { document.getElementById("txtHint").i ...

Minimize the amount of information retrieved and shown based on the timestamp

I am currently working on storing and retrieving the date of a user request. For creating the timestamp, I use this code: const date = firebase.firestore.FieldValue.serverTimestamp(); This is how I fetch and display the data: <tr class="tr-content" ...

What is the most efficient method for exporting Express route functions for promise chaining?

Currently, I am in the process of refactoring an API route to utilize ES6 promises instead of callbacks, so as to avoid callback hell. Upon successful conversion to a promise chain, my intention was to extract the .then() functions into a separate file fo ...

What is causing the error "Next is not a function" to occur when exporting a Middleware function to the module.exports object?

In my logger.js module, I have a middleware function that I import into app.js and utilize. // ------ File : logger.js ------ // function log(req, res, next) { console.log('Logging details ... '); next(); } module.exports = log; // ---- ...

Display JSON values in sequence using Material-UI animations

I have received an array of JSON data from the API that looks like this: "fruits": [ { "id": "1", "fruit": "APPLE", }, { "id": "2", "fruit": ...

Translate data from two "contact form 7" date fields into JavaScript/jQuery to display the date range between them

NEW UPDATE: I was able to get it working, but the code is a bit messy. If anyone can help me clean it up, I would greatly appreciate it. <div class="column one-fourth" id="date-start">[date* date-start date-format:dd/mm/yy min:today+1days placeholde ...

Employing a general-purpose function in a recursive manner

My function that removes properties from an object and returns a new one works fine, but it runs into issues when dealing with nested arrays of objects. How can I tackle this challenge? interface User { id: number; name: string; items?: User[]; } co ...

Phonegap's JavaScript canvas feature is experiencing issues

Recently, I came across a JavaScript bouncing ball animation that works perfectly on the Chrome browser when used on a PC. However, when I tried running it using Phonegap Eclipse Android emulator, I encountered an issue where the canvas appeared blank and ...

Regular expressions in JavaScript to match characters that are not the first character and are

I prefer not to include the first letter of characters such as _-., but they can be used between other characters '(^[a-zA-Z0-9-_. ]*$){1,10}' ...