The toThrow() function in Jest seems to be malfunctioning

Even though my JS code throws the correct error, it still fails. Here is the relevant Jest code block:

 describe('operate', () => {
    test("works with addition", () => {
        expect(evaluate_expression("3+5")).toEqual(8);
    });
    test("works with substraction", () => {
        expect(evaluate_expression("128-29")).toEqual(99);
    });
    test("works with multiplication", () => {
        expect(evaluate_expression("25*5")).toEqual(125);
    });
    test("works with division", () => {
        expect(evaluate_expression("990/99")).toEqual(10);
    });
    test("division 0 is handled", () => {
        expect(evaluate_expression("5/0")).toThrow('Division by zero');
    });
});

JavaScript code snippet:

function append_to_display(value) {
    if (start == false)
        document.getElementById('display').value += value;
    else {
        document.getElementById('display').value = value;
    };
};

function calculate() {
    try {
        const expression = document.getElementById('display').value;
        console.log(expression);
        const result = evaluate_expression(expression);
        document.getElementById('display').value = result;
        document.getElementById('current_value').textContent = result;
    } catch (error) {
        document.getElementById('display').value = 'Error';
    }
};

function evaluate_expression(expression) {
    const output_queue = [];
    const operator_stack = [];
    const operators = { '+': 1, '-': 1, '*': 2, '/': 2 };

    const tokens = expression.match(/([0-9]+|\+|\-|\*|\/)/g);

    tokens.forEach(token => {
        if (!isNaN(token)) {
            output_queue.push(parseFloat(token));
        } else if (token in operators) {
            while (
                operator_stack.length > 0 &&
                operators[token] <= operators[operator_stack[operator_stack.length - 1]]
            ) {
                output_queue.push(operator_stack.pop());
            }
            operator_stack.push(token);
        } else {
            throw new Error('Invalid expression');
        }
    });

    while (operator_stack.length > 0) {
        output_queue.push(operator_stack.pop());
    }

    const result_stack = [];
    output_queue.forEach(token => {
        if (!isNaN(token)) {
            result_stack.push(token);
        } else {
            const b = result_stack.pop();
            const a = result_stack.pop();
            switch (token) {
                case '+':
                    result_stack.push(a + b);
                    break;
                case '-':
                    result_stack.push(a - b);
                    break;
                case '*':
                    result_stack.push(a * b);
                    break;
                case '/':
                    if (b === 0) {
                        throw new Error('Division by zero'); // HERE IS THE PROBLEM
                    }
                    result_stack.push(a / b);
                    break;
                default:
                    throw new Error('Invalid operator');
            }
        }
    });

    if (result_stack.length !== 1) {
        throw new Error('Invalid expression');
    }

evaluate_expression() is triggered by calculate() when the "=" button is clicked on the calculator.

This is the specific line causing the issue in the JavaScript code:

    if (b === 0) {
         throw new Error('Division by zero'); // HERE IS THE PROBLEM
    }

I have attempted to use rejects with expect here, but it has not worked as expected.

Answer №1

To utilize Jest's toThrow functionality, it is necessary to provide a function to the expect method, meaning you should encapsulate the code you wish to test within a function.

https://jestjs.io/docs/expect#tothrowerror

Make sure to enclose the code in a function, as failing to do so will result in the error not being captured and the assertion failing.

test("division by zero is handled", () => {
    expect(() => evaluate_expression("5/0")).toThrow('Division by zero');
});

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

Find keys in an array based on a specified value

I need to retrieve an array of keys from an object that match a specified value ...

What is the best way to create rotational movement for an object in a-frame?

Is there a way to have my entity rotate/spin on the Y-axis? I attempted the following: <a-entity position="-1 0.5 3" animation="property: rotation; to: 0 0 0 ; loop: true; elasticity:1000; dur: 10000" rotation="90 0 0"> <a-box position="1 0 ...

The WHATWG URL API allows creation of a new URL using the new URL

I've been experimenting with node and attempting to create an instance of the URL class to utilize its useful properties. Here's what I tried: const { URL } = require('url'); (...) http.createServer((request,response) => { let u ...

What is the best way to retrieve the current page name in DNN and store it in a JavaScript

Having trouble capturing the current DNN page name and assigning it to a variable in javascript. Despite searching online, I haven't been able to find the right code for it. <script type="text/javascript"> var tabName = <% =TabName %>; &l ...

How can I integrate both the ui-bootstrap datepicker and timepicker in an AngularJS application?

I am currently developing a web application that utilizes UI-Bootstrap's datepicker and timepicker directives. The datepicker is set up as a simple popup dialog, while the timepicker appears on the page next to the datepicker. However, I am facing ch ...

Stop Caching with Jquery Infinite Scroll (IAS)

I am using jQuery + IAS to implement infinite scroll functionality on my website. However, I have encountered an issue where the cache is being disabled when making requests for new content. Specifically, the URL that is accessed to retrieve the next page ...

Month and year selection feature in ExtJS 4 catalog

I recently came across an interesting Fiddle that featured a Month and Year picker for apps. After finding this Fiddle here, I noticed that it was built using Extjs 5.0, and it worked perfectly. However, when attempting to switch it to version 4.2.1, the l ...

Test files utilizing Sequelize fail to access the test environment

Currently, I am utilizing sequelize as an ORM and jest for testing purposes. I have set up two databases using docker compose - one for testing and another for development. The environment variables are correctly configured in console.log. However, for so ...

Troubleshooting Node.js and Express: Adding to array leads to displaying "[object Object]"

As a newcomer to web development and currently enrolled in a course for it, I am in the process of creating a test web server before diving into my main project. In this test scenario, my goal is to extract the value from a text block and add it to a respo ...

What effect does setting AutoPostBack to "true" in an ASP dropdownlist have on the fireEvent() function?

I am currently working on an aspx page. This page includes three dropdown lists and a button, all of which are populated dynamically based on the code written in the code-behind file (.cs file). To achieve this, I need to utilize two event handler methods ...

What is the best way to determine the number of subchildren within a parent div using JavaScript or jQuery?

Can anyone assist me with counting the number of child divs inside a parent div using JavaScript or jQuery? I'm not very experienced in these languages. Below is my code snippet: $(function () { var parent = document.getElementById('parent& ...

An issue with displaying images has been identified within Next.js, resulting in an error message related to the hostname

Encountering an error when using next js Image next.config.js: module.exports = { images: { domains: ['localhost'], }, }; Error image: https://i.stack.imgur.com/RvsdH.png I am struggling to understand how to correctly set up the image ...

Obtain the text content of a div using JavaScript

Hello, I am new to Javascript! I have a table structure that looks like this: <table id='master_tbl'> <tbody> <tr id="master_hr'> <td class="myclass"> <table> <tbody ...

Automatically conceal a div or flash message after a short period of time by utilizing CSS3 in a React

I am relatively new to the React environment and recently created a basic component for a bookmarking feature. Essentially, when the favourite icon is clicked, an ajax call is sent > a record is created in the database > on ajax success, a flash me ...

The issue of the highlighted row not disappearing persists even after clicking on the adjacent table row

When selecting the gear icon for the menu option in a table row, I would like the background to turn yellow. I attempted the following code to highlight the table row: var view = Core.view.Menu.create({ model: model, menuContext: { ibmm: ibmm }, ...

Why isn't the correct component being shown by react-router?

I have encountered an issue with my code. When I type localhost:8080 in the browser, it displays the App.js component as expected. However, upon navigating to localhost:8080/#/hello, it still shows the App.js component instead of hello.js. Interestingly, ...

Transfer an object to $state.go

I'm having trouble solving this issue. Here's the state I am working with: var myState:ng.ui.IState = <ng.ui.IState> { url: '/new/{order.orderNumber}', controller: 'OrderController', controll ...

Unable to import the configuration module that is located three directories away in a Node.js environment

Within user.controller.js, there is a line that reads as follows: const config = require(".../config");. To provide some context, here is a visual representation of my directory structure: https://i.stack.imgur.com/dCkp1.png ...

Instructions for showing a timer on a webpage from a managed bean by utilizing JavaScript

I'm currently tackling the challenge of passing a Date from a managed bean to JavaScript and then displaying it as a timer in the format "hh:mm:ss aa". I've attempted it but so far, no luck. Code: DateTimeManagmentMB.java (Managed Bean) import ...

Guide to Establishing a Connection to WCF Service using Ionic Project and AngularJS

Greetings, I am currently experiencing an issue tasked with connecting my Ionic project to a WCF service located on another PC (running a C# Application) within the local network. I have verified that the network connection between the PCs is functioning p ...