Exploring the world of mocking tests using Jest and inputs

Is there a way to create a jest test specifically for this function?

const input = require('prompt-sync')();

export function choices(): void {
    const choice = input("Choose a letter");
    if (choice === "a") {
        console.log("Airplane");
    } if (choice === "b") {
        console.log("Balloon");
    } else {
        console.log("Neither");
    }

}

I am aware that mocking is necessary in this scenario. However, I am uncertain about how to implement it when the input is stored within the function itself rather than being passed as a parameter. I would prefer not to alter this setup.

Answer №1

To mock the prompt-sync module in your tests, you can utilize the jest.mock function. This module returns a function that provides your input, so your Jest.mock setup would look something like this:

const mockInput = jest.fn();
jest.mock("prompt-sync", () => () => mockInput);

Make sure to include this setup before importing the module in your test file.

Here is a complete example:

const mockInput = jest.fn();
jest.mock("prompt-sync", () => () => mockInput);

import { choices } from "../path/to/file";

describe("test", () => {
  let consoleSpy: jest.SpyInstance;

  beforeEach(() => {
    consoleSpy = jest.spyOn(console, "log");
  });

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

  it("should call the input", () => {
    choices();

    expect(mockInput).toHaveBeenCalledWith("Choose a letter");
  });

  it("should call 'A'", () => {
    mockInput.mockReturnValue("a");

    choices();

    expect(consoleSpy).toHaveBeenCalledWith("Airplane");
  });
});

I recommend refactoring your code to improve its testability.

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

Angular 6 provides a regular expression that specifically targets the removal of any characters that are not numbers and enforces the allowance of

I have tried various solutions to restrict input in an Angular material input box, but none seem to be effective for my specific case. I need the input field to only allow numbers and a decimal point. Any other characters should be automatically removed as ...

transfer item between a mother and offspring

In my project, I have a convention object that needs to be passed as an input to a child component. The convention ID is displayed correctly in the child's template, however, I encounter an issue where the convention appears as undefined when trying t ...

Creating an interface for writing types in Firebase functions/storage/database

What are the TypeScript types for Firebase functions, storage, and admin? I'm fairly new to TypeScript and currently in the process of updating my JavaScript code to TypeScript. Within my code, I am generating a context object. const context = { ...

Updating a null value within the database was done successfully

Currently, I am working with angular CLI version 8.1.0 and have a user list displayed on a mat table. Upon clicking on a specific user, a new page opens up containing two buttons - "approve" and "reject". The issue I am facing is that when I click on "ap ...

Creating an Angular table using reactive forms: a step-by-step guide

After reviewing the HTML snippet provided below, it is evident that there is a table with looping through mat cell using *matCellDef="let model". Inside each cell, there are input fields which are reactive forms. Each row or cell needs to have it ...

How can models be aggregated in SQL by connecting them through other models?

I am working with a backend express API that utilizes sequelize. In my sequelize models, a Citizen is linked to a Street, which in turn is associated with a Town, and the Town is connected to a State. I can easily count the citizens on a specific Street by ...

Remove the package from the @types folder within the node_modules directory

I currently have the 'mime' library in my node_modules directory and I am looking to completely remove it from my project, along with its @types files. The reason for this is that the old mime package is not functioning correctly for me, so I wan ...

Building a Vuetify Form using a custom template design

My goal is to create a form using data from a JSON object. The JSON data is stored in a settings[] object retrieved through an axios request: [ { "id" : 2, "name" : "CAR_NETWORK", "value" : 1.00 }, { "id" : 3, "name" : "SALES_FCT_SKU_MAX", "val ...

Leverage the specific child's package modules during the execution of the bundle

Project Set Up I have divided my project into 3 npm packages: root, client, and server. Each package contains the specific dependencies it requires; for example, root has build tools, client has react, and server has express. While I understand that this ...

When using React with TypeScript, there seems to be an issue where using history.push to change the URL results in rendering the 404 page instead

I have gone through all the previous answers but none of them could solve my problem. I am new to React and currently working on a personal project where I use React with TypeScript, Redux, and Material UI. For some reason, when I try to redirect from ins ...

Tips for testing the 'error' color (red) in Material UI using Jest and React Testing Library

I am looking to verify the <AppBar position='relative' color='error' data-testid='appbar'> ... </AppBar> and ensure that it has a test('Appbar background color must be red', () => { render(< ...

What is the best way to showcase a standalone JSON object within the template?

I have a detailed component that is designed to show the 5-day forecast for a specific city. I have successfully retrieved the data using the http.get(Url) method. However, I am unsure of how to bind this JSON data to my view. I am familiar with displayi ...

Arrange the array based on the order of the enumeration rather than its values

Looking to create an Array of objects with enum properties. export enum MyEnum { FIXTERM1W = 'FIXTERM_1W', FIXTERM2W = 'FIXTERM_2W', FIXTERM1M = 'FIXTERM_1M', FIXTERM2M = 'FIXTERM_2M', FIXTERM3M = 'FIX ...

Obtaining undefined values for req and resolvedUrl in GetServerSideProps function

In my project, I am currently using next.js version ""next": "^12.1.4"" and node version ""@types/node": "^14.14.6". I have created a function called getServerSideProps with parameters req and resolvedUrl. When the ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

Is there a different approach available since the array function "some" does not restrict type even when a type predicate is implemented?

It is expected that when using the array function "some" along with a type predicate and return statement, the TypeScript compiler would narrow down the type of dashArray. Is it reasonable to expect this behavior from the TypeScript compiler or am I incor ...

Retrieve TypeScript object after successful login with Firebase

I'm struggling with the code snippet below: login = (email: string, senha: string): { nome: string, genero: string, foto: string;} => { this.fireAuth.signInWithEmailAndPassword(email, senha).then(res => { firebase.database().ref(&ap ...

Basic exam but located in a place that is not valid

Here is a test I am working on: // import {by, element, browser} from "protractor"; describe('intro', () => { beforeEach(() => { browser.get(''); }); it('should have multiple pages', () => { let buttonOn ...

The presence of a method is triggering an Error TS2741 message stating that the property is missing in type

Here is a simplified code snippet that highlights the issue I am facing: class Test { prop1 : boolean prop2 : string method() { } static create(prop1 : boolean, prop2 : string) : Test { let item : Test = { prop1: prop1, prop2: pro ...

Angular is reporting that the check-in component is nonexistent

I encountered an error in my Angular 8 application while working on a component. The error seems to be related to nested components within the main component. It appears that if the component is empty, the error will be shown, but if it's not null, th ...