Is it possible that jest is unable to catch the exception?

I have a simple function that looks like this:

function foo({ platform }) {
  if (platform === 'all') {
    throw new Error('Platform value can only be android or ios');
  }
  
  return `${platform}`;
}

After writing unit tests, the results were not as expected. Here is the test code:

it('should correctly return the result based on platform', () => {
    expect(foo({ platform: 'ios' })).toBe('ios');
    expect(foo({ platform: 'android' })).toBe('android');
    expect(foo({platform: 'all'})).toThrow(new Error('Platform value can only be android or ios'));
  });

Unfortunately, the final test case failed without providing useful information:

 FAIL  src/utils/__test__/foo.test.ts
  ● foo() › should return correct result with platform

    Platform value can only be android or ios

      16 | }) {
      17 |   if (platform === 'all') {
    > 18 |     throw new Error('Platform value can only be android or ios');
         |           ^
      19 |   }
      20 |   
      21 |   return `${platform}`;

      at xx (src/utils/foo.ts:18:11)

Even after wrapping the entire expect statement in a try-catch block, the test continued to fail.

Answer №1

When using the <code>expect function in Jest, it is important to note that the toThrow method will only work if expect is passed a no-arg function that can be called to trigger the exception.

/* This specific test requires this setup */
expect(() => foo({platform: 'all'})).toThrow();

This limitation exists because JavaScript does not have built-in functionality to defer function arguments automatically, preventing expect from pausing evaluation of its arguments. Therefore, Jest requires developers to provide a callback function for triggering actions at the appropriate time.

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

Decoding JSON data in a Webmethod from an AJAX call

I am faced with a challenge regarding passing a JSON object from JavaScript to a VB.Net WebMethod via an ajax request and then attempting to deserialize it. Despite successfully passing the object, I encounter an error during deserialization: Error convert ...

Guide to verifying all chosen options in a multiple select field using EJS

I am looking for the most effective way to check all selected options in my select dropdown when data is being edited. Here is an example of my select dropdown that supports multiple selections: <select name="tags[]" class="multi-select" multiple="" i ...

Trouble embedding iframes in local files?

I have recently created a file which includes the following code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8> <style> iframe { height: 500px; width: 600px; } ...

How to create a loop in Selenium IDE for selecting specific values from a drop-down list?

Is there a way to use Selenium IDE and JavaScript to test a drop-down box with specific items, not all of them, and continuously loop through until the entire list is covered? Any tips or recommendations on how to accomplish this? ...

Adding Bootstrap to container-specific styling in SCSS

I am currently in the process of upgrading to the most recent version of reactstrap & Bootstrap. Previously, I had reactstrap in my package.json file and downloaded Bootstrap SCSS in my client/src/styles/bootstrap directory. Now, my updated package.json c ...

Searching for a specific data point within the latest entry of a JSON file using Javascript

I am currently in the process of utilizing a sensor to measure temperature, which is then stored in a mongo database. This data can be accessed as a JSON file by visiting ('/data'). My goal is to determine the latest entry and extract the temper ...

Retrieve data from an array of objects nested within another object

Imagine a scenario where there is an object containing an array of objects. let events = { "id": 241, "name": "Rock Party", "type": "party", "days": [ { "i ...

Bring JavaScript Function into Vue's index.html File

Recently in my code files, I noticed the following: function example() { console.log("testing"); } In another file, I have something like this: <head> <script src="../src/example.js" type="text/babel"></sc ...

Error: scrollreveal JavaScript is not properly defined

Desperately seeking guidance on a particular code snippet... window.sr = ScrollReveal({ reset: true }); sr.reveal('.whitecircle, .circleStatsItemBox, .circleStat', { duration: 200 }); function circle_program() { var divElement = $(&apo ...

Error: Attempting to access 'title' property of undefined object leads to Uncaught TypeError

I am attempting to extract content from a Google Blogger Feed that can be found at this link. I am using JavaScript code from here. When inspecting the elements, I encountered a specific red warning message: Uncaught TypeError: Cannot read property ' ...

Issues with Angular route links not functioning correctly when using an Array of objects

After hard coding some routerLinks into my application and witnessing smooth functionality, I decided to explore a different approach: View: <ul class="list navbar-nav"></ul> Ts.file public links = [ { name: "Home&quo ...

Exploring the power of Async/Await with Angular 5 HttpClient and forEach

I am struggling to implement async/await in my code to show a spinner when I click on a button and hide it once I have all the data. Below is a simplified version of what I have: .ts: isLoading: boolean = false; onLoad() { this.isLoading = true; ...

Combining multiple template filters in ng-table with the power of CoffeeScript

Combining AngularJS, ng-table, and coffeescript has been quite a task for me. I've been trying to create a multiple template filter within coffeescript and pass it into my angularjs template. One of the challenges I'm facing is with a combined & ...

The function is failing to return the expected value received from the observable subscription

I am attempting to verify the existence of a user in an Angular's in-memory API by validating their username. The function checkUsernameExists(username) is supposed to return an Observable<boolean> based on whether the API responds with undefine ...

What is the best approach for creating a test case for a bootstrap-vue modal component

Exploring ways to effectively test the bootstrap vue modal display function. On the project page, the modal toggles its visibility using the toggleModal method triggered by a button click. The modal's display style is switched between 'none' ...

What is the specific purpose of the 'extend' keyword in Typescript?

Recently, I have been delving into the realm of Javascript/Typescript/React as a PHP developer. During my learning process, I encountered a few perplexing issues that I could not fully grasp. In light of this, I am reaching out to the experienced indiv ...

There seems to be an issue with the OpenAPI generator for Angular as it is not generating the multipart form data endpoint correctly. By default

Here is the endpoint that needs to be addressed: @PostMapping(value = "/file-upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public List<FileReference> handleFileUpload( @RequestPart(value = "file", name = "f ...

Displaying content on the <div> element

Looking for recommendations for a jQuery plugin or JavaScript solution that allows me to load a full "view" into a <div> when a user clicks on a link. The challenge I'm facing is that I have 8 pages, with the Homepage consisting of 3 divisions: ...

Ways to change the visibility of a view depending on a state in vuex?

If I have a button <Button> Log me in! </Button>, and I want to dynamically change its style based on the state of my Vuex app (state.user is not null). How should I properly implement this functionality? I'm considering creating a field ...

Error: Issue determining the type of variable. Unable to eliminate type 'any'

I am trying to load some widgets from a template object (possibly JSON in the future). Here's an example: type RectangleTemplate = { name: 'Rectangle'; props: { width: number; height: number; } }; type ButtonTemplate = { nam ...