Do I have to wait for promises to be resolved or does expect(...).toBe handle it automatically?

Testing with Protractor can be quite challenging and confusing, especially for those new to it.

I currently have the following setup:

`SomeTestFile.spec.ts`
describe('A test: ', () => {

    beforeEach(() => {
      ....
    }

    it ('Should validate a label', async() => {
      await helper.validateALabel(label);
    }   

    ....
}

In the helper class:

helper.ts
export class Helper {
  ....

  public validateLabel(label: String): Promise<void> {
    expect(label).toBe('This is the string of the label');
  }

  ....
}

My question is whether I need to await the expect(label).toBe(...)?

Should I use

await expect(label).toBe(...)

OR is it okay as it is (and if so, why do I keep receiving Unhandled Promise Rejection Warnings)?

expect(label).toBe(...)

Answer №1

It does not.

You must wait for your promise to resolve and then compare the result.

// example promise function
const checkLabel = (label) => new Promise(r => r(true))

it ('validates a label', async () => {
  const isValid = await checkLabel(label)

  expect(isValid).toBeTruthy()
})

In this scenario, it appears that you are incorrectly specifying the return type:

public confirmLabel(label: String): Promise<void> {
  expect(label).toBe('This is the string of the label');
}

Here, it actually does not return a Promise<void>, but simply void, so there is no need for async/await at all.

Answer №2

If you want:

test('returns as pineapple', async () => {
  await expect(Promise.resolve('pineapple')).resolves.toBe('pineapple');
});

Check out the details at https://jestjs.io/docs/en/expect#resolves

Answer №3

Utilizing expects in step definitions is a recommended practice. By retrieving the value from the helper class, you can include assertions in your step definitions to determine whether the test step passes or fails.

`AnotherTestFile.spec.ts`
describe('Testing functionality: ', () => {

    beforeEach(() => {
      ....
    }

    it ('Verifying a specific element', async() => {
      await expect(helper.validateAnElement(element)).toBe('This is the content of the element');
    }   

    ....
    }

helper.ts

export class Helper {
  ....
 function validateElement(element) {
    return new Promise((resolve, reject) => {
        return resolve('This is the content of the element');
    })
 }

  ....
}

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

Easily Organize Your Data with Kendo React Grid: Rearrange Columns and Preserve Your Custom Layout

Currently, I am working on implementing a Kendo React grid with the option set to reorderable={true} for allowing column reordering. However, I am facing difficulty in determining how to save the new order of columns. Which event should I use to detect whe ...

issue TS2322: The function returns a type of '() => string' which cannot be assigned to type 'string

I have recently started learning Angular 6. Below is the code I am currently working on: export class DateComponent implements OnInit { currentDate: string = new Date().toDateString; constructor() { } ngOnInit() { } } However, I am encounterin ...

Encountering TypeScript error in the beforeRouteUpdate hook with Vue and vue-property-decorator

I am developing an application using Vue 2 with TypeScript and vue-property-decorator. Within my component, I am utilizing the beforeRouteEnter/beforeRouteUpdate hooks. One of the methods in my component is findProjects, which I want to call within the bef ...

Error in Jest: Type error - res.status function is undefined

I have implemented a middleware for token verification using the following code: import { Request, Response, NextFunction } from "express"; import jwt from "jsonwebtoken"; class TokenVerifier { public verify(req: Request, res: Resp ...

Angular: Using cross-field validation to invalidate bootstrap input fields

In my reactive form, I have two fields named from and to. I am in need of a validation mechanism that checks if the value in the from field is lower than the value in the to field every time either of them is changed. To achieve this validation, I have imp ...

Implementing a dependent <select> within an HTML table is a useful feature to enhance user experience and organization of

I have set up a table with editable columns where values can be selected from a drop-down menu. I achieved this by using HTML select. The options in the 'Category tier 2' column are based on the selection made in the 'Category tier 1' c ...

Testing Angular components, modifying ActivatedRoute parameters dynamically to cover various test scenarios

Component: @Component({ selector: 'app-test', templateUrl: './test.component.html' }) export class TestComponent implements OnInit { useCase: string; constructor( private route: ActivatedRoute, ) {} ngOnInit() { t ...

Is there a way to verify if multiple variables in Typescript are null or undefined?

Background To address the issue of checking whether a specific variable is null or undefined, I created the isNullish function. The implementation of this function is shown below. type Nullish = null | undefined; const isNullish = (target: unknown): targe ...

Turn off the warning message that says 'Type of property circularly references itself in mapped type' or find a solution to bypass it

Is there a way to disable this specific error throughout my entire project, or is there a workaround available? The error message states: "Type of property 'UID' circularly references itself in mapped type 'Partial'.ts(2615)" https:/ ...

How can I make the snackbar open multiple times in a row?

Check out this codesandbox I created to show an issue. When you click the button, a MUI snackbar opens. However, if you close it and try to reopen it, nothing happens. Do you think the problem is related to how I'm using hooks? Explore the sandbox h ...

How can I inform Typescript that a function will never return null in this specific scenario?

Need help with implementing typescript strictNullChecks in an Angular 5 project. The form structure is as follows: this.signinForm = this.fb.group({ emailAddress: ['', NGValidators.isEmail()], password: ['', Validators.required], ...

Successfully upgraded Angular 7 to 8, however, encountering an issue with the core not being able to locate the rxjs module

After updating my Angular version from 7.X to 8.2.5, everything seemed fine until I started getting errors related to the rxjs module within the angular/core package. Despite having the latest version of rxjs (6.5.3), the errors persisted even after removi ...

The absence of jQuery and bootstrap in the node_modules directory was detected

Hello everyone! I hope your day is going well. Recently, I embarked on an Angular project from the ground up. After installing all the necessary packages via npm, I decided to incorporate Bootstrap into my project. However, I quickly discovered that Boots ...

Hiding components in Angular 4/5 through routing decisions

Just getting started with routing in Angular 4/5, I am currently following the tutorial provided on the official Angular website. I have an Angular application and I want to create two separate pages. Currently, the main page is located at localhost:8870/d ...

How should one sort the Object and Array derived from Observables within a foreach loop in an Asynchronous Angular 4/5 environment?

Having an issue with the order of execution in my code. I'm running a method (myTableService.getAllTables()) that returns a JSON to create an object (this.myTables). Then, for each element in this.myTables, I execute another request (this.myTableS ...

Learn the process of inserting a table in ExcelJS specifically for Angular applications

I encountered an issue when attempting to add a table with data. An error message stating "AddTable is not function" appeared. let workbook = new ExcelJS.Workbook(); let worksheet = workbook.addWorksheet("Data"); worksheet.addTable({ name: 'My ...

Here is a method to transform the JSON object into a string as demonstrated below:

Presented below is a JSON object: { "category": "music", "location": { "city": "Braga" }, "date": { "start": { "$gte": "2017-05-01T18:30:00.000Z" }, "end": { "$lt": "2017-05-12T18:30:00.000Z" } } } I am looking t ...

What is the purpose of using 'ref' in conjunction with useCallback instead of just utilizing useCallback on its own?

While working on my React project, I came across some libraries that used 'useCallback' in a different way than I'm used to. Below is the code snippet showcasing this approach. Despite my initial thoughts, I still believe there's no sig ...

Tips for debugging Typescript code in Visual Studio Code using ts-node-dev and ensuring accurate line numbering

Launching my Typescript project involves using the following command: ts-node-dev --preserve-symlinks --inspect=0.0.0.0 -- src/server.ts While I am able to debug it using Visual Studio Code, the debugger tends to break at incorrect lines. My assumption ...

Is there a way to designate an image to a variable or object property through manual assignment?

Is it feasible to manually link an image file from the assets folder to an object property? Let's say I have an image stored at 'assets/images/ProfilePlaceholder.png'. Would it be possible to assign the image file as a value to an object pr ...