Dealing with throwing Exceptions in jest: A guide for developers

I have developed a method that throws an exception when the provided password does not match a regex pattern. I attempted to handle this in Jest.

  it('Should prevent insertion of a new user if the password doesn't match the regex', async () => {
    jest.spyOn(usersModel, 'create').mockImplementationOnce(() =>
      Promise.resolve({
        name: 'some name',
        email: 'some <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff9a929e9693bf9a929e9693d19c9092">[email protected]</a>',
        pass: 'some pass',
      } as IUser)
    )

    const newUser = await usersService.create({
      name: 'some name',
      email: 'some <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abcec6cac2c7ebcec6cac2c785c8c4c6">[email protected]</a>',
      pass: 'some pass',
    })
    expect(newUser).toThrow()
  })

I also tried using toThrow('error message') and

toThrow(new BadRequestException())
, but neither of them worked.

Here is the error message from Jest:

 UsersService › Should not insert a new user cause password do not match regex

    Password does not match regex

      49 |     const emailRegex = /[^@ \t\r\n]+@[^@ \t\r\n]+\.[^@ \t\r\n]+/
      50 |
    > 51 |     if (!pass.match(passRegex)) throw new BadRequestException('Password does not match regex')
         |                                       ^
      52 |     if (!email.match(emailRegex)) throw new BadRequestException('Email does not match regex')
      53 |
      54 |     const saltRounds = 10

      at UsersService.create (users/users.service.ts:51:39)
      at Object.<anonymous> (users/users.service.spec.ts:135:21)

Answer №1

To validate the password against a regex pattern when inserting a new user, you can utilize the .resolves matcher within your expect statement as shown below:

it('Should not insert a new user cause password do not match regex', async () => {
  jest.spyOn(usersModel, 'create').mockImplementationOnce(() =>
    Promise.resolve({
      name: 'some name',
      email: 'some <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94f1f9f5fdf8d4f1f9f5fdf8baf7fbf9">[email protected]</a>',
      pass: 'some pass',
    } as IUser),
  );

  // Remove `await` keyword, because you will pass a promise in the expect function
  const newUser = usersService.create({
    name: 'some name',
    email: 'some <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="07626a666e6b47626a666e6b2964686a">[email protected]</a>',
    pass: 'some pass',
  });

  // Add `await` keyword and `rejects` matcher with the `toThrow`
  await expect(newUser).rejects.toThrow('Password does not match regex');
});

If desired, an alternative approach using a try/catch statement is presented below (although it's recommended to stick with the previous method):

it('Should not insert a new user cause password do not match regex', async () => {
  expect.assertions(1)

  jest.spyOn(usersModel, 'create').mockImplementationOnce(() =>
    Promise.resolve({
      name: 'some name',
      email: 'some <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dabfb7bbb3b69abfb7bbb3b6f4b9b5b7">[email protected]</a>',
      pass: 'some pass',
    } as IUser),
  );

  // Incorporate a `try/catch` statement
  try {
    const newUser = await usersService.create({
      name: 'some name',
      email: 'some <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e4b434f47426e4b434f4742004d4143">[email protected]</a>',
      pass: 'some pass',
    });
  } catch (e) {
    expect(e.toString()).toMatch('Password does not match regex');
  }
});

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

Ways to input a return value that may be an array depending on the input

I'm struggling to properly type the return value in TypeScript to clear an error. function simplifiedFn( ids: string | string[], ): typeof ids extends string[] ? number[] : number { const idsIsArray = Array.isArray(ids); const idsProvided = idsI ...

Guide to implementing the collapsible start and stop button feature in Angular

Having an issue in my Angular application with the dashboard page. I've created a button for start or stop (toggle functionality) but it's not working as expected. .component.ts toggleCollapse(jammer) { this.jammer.isCollapsed ? 'START& ...

A guide to showcasing items based on their categories using React.js

After successfully displaying Categories from a port (http://localhost:5000), accessing my MongoDB database, I encountered an issue when attempting to display the products for each category separately. Despite trying the same method as before, I keep rec ...

Tips for removing the y-axis line in ChartJs

How can I hide the y axis line in a bubble chart? I attempted to use the code snippet below but it did not work as expected. yAxes: [{ angleLines: { display: false } }] ...

An error occurred during runtime due to a TypeError when trying to execute the 'setItem' function on 'Storage'. The error message indicates that 2 arguments are required for this function, but only 1 argument

Having an issue with the local storage not working and the screen showing up as white in the browser. 5 | const getFromLocalStorage = () => { 6 | if (typeof window !== undefined) { > 7 | const value = localStorage.getItem(& ...

Bootstrap datepicker not applying datepicker-options as expected

I have been trying to pass all my options in a JSON file according to the instructions on http://angular-ui.github.io/bootstrap/#/top, but unfortunately, I haven't been able to get it to work. I've been experimenting with the Plunkr provided on t ...

Avoiding future clicks with a delay in VUE: A guide

Is there a way to prevent the next click for 600ms after an initial click? I want to temporarily "disable" all a tags for 600ms after one is clicked. Any help would be appreciated. VUE <ul> <li v-for="item in navigation" :key=& ...

What steps should I take to ensure my three.js project is compatible with iPhone testing?

I recently developed a new AR project that allows users to interact with AR content through their phone camera on a website. However, I am facing an issue where I cannot easily test my website on an iPhone whenever I make changes to the code. Currently, ...

Retrieving time zone using offset with javascript

I am looking for a way to schedule time-based events on my server operating in UTC time. For the user interface, I need to input 2 parameters: The local time when the scheduled event should trigger The timezone offset Instead of displaying timezone n ...

I am facing errors while running npm run build in my Vue CLI project, however, npm run dev is running smoothly without

I am encountering an issue when running npm run build as it generates a series of errors, whereas npm run dev runs smoothly without any errors. I have attempted to resolve this by modifying the public path in webpack.config.js to ./dist, but unfortunately ...

CSS- Strategically placing and centering images above specific keywords in (any) HTML content without disrupting the flow of text

My main objective involves dynamically inserting images above text on any given page using a content script. The challenge lies in maintaining the proper alignment of the text after adding the images. To achieve this, I surround the words where the image i ...

Can you explain the meaning of the error message "Thread 3: EXC_BAD_ACCESS (code=2, address=0x16dbc7ff0)" in the exception error code?

While debugging my iOS Xcode project, I encountered a run time error on an iPhone 8 device running iOS 15.5. My setup includes Xcode version 13.4.1 on a Mac Pro with macOS Monterey version 12.5. The error message pinpointed the issue to a line of code whe ...

Observable subscription results in a return of undefined

My observable is being filled with data from the backend using a service. The backend is providing the correct data, but I am having trouble building a pie chart with the values from the observable. The relevant part of the code is as follows: this.dataSe ...

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}' ...

Adding tween.js seems to have caused the button click event to stop triggering

After adding the code line to tween my display box, the click event is no longer triggered. There are no errors in the console. How can I resolve this issue and what might have caused it? createjs.Tween.get(directionsbox, { loop: false }).to({ x:800, y: ...

Error: Docker/Next.js cannot locate module '@mui/x-date-pickers/AdapterDateFns' or its respective type definitions

When I run the command npm run build, my Next.js application builds successfully without any issues. However, when I try to build it in my Dockerfile, I encounter the following problem: #0 12.18 Type error: Cannot find module '@mui/x-date-pickers/Ada ...

Achieving Vertical Centering of Text in Bootstrap 5 Buttons with Flex Box to Prevent Overlapping Icons

How can I prevent the text on a Bootstrap 5 button with horizontally and vertically centered text, along with a right aligned icon, from overlapping when it wraps? Additionally, how do I ensure that the icon stays vertically centered when the button text w ...

Troubleshooting problems with contenteditable and input in Firefox and Safari on Angular 5

Currently, I am in the process of creating a table with cells that are editable. However, I am facing a challenge in updating the visual and typescript code simultaneously. I have explored various alternatives but unfortunately, none of them seem to work. ...

JavaScript: Converting an Array to a String

Having trouble making the string method work with an array - it keeps showing up as empty. let url = "https://api.myjson.com/bins/be7fc" let data =[]; fetch(url) .then(response => response.json()) .then(result => data.push(r ...

Fade effect not working with Bootstrap Modal

I am encountering an issue with the Twitter Bootstrap modal while trying to display post details on WordPress. The problem is that when the modal opens, the entire screen turns grey and nothing in the modal is clickable. I can only exit this mode by pressi ...