简体   繁体   中英

Returning a Promise from "describe" is not supported. Tests must be defined synchronously

Particular test passed but I am getting this.

    console.log node_modules/jest-jasmine2/build/jasmine/Env.js:502
          ● 

Test suite failed to run

            Returning a Promise from "describe" is not supported. Tests must be defined synchronously.
            Returning a value from "describe" will fail the test in a future version of Jest.

        > 4 | describe('handlers.getSemesters', async () => {

Here is complete test code

describe('handlers.getSemesters', async () => {
      it('should return an array of Semesters', async () => {
        academicCalendarRequest.request = jest.fn();
        academicCalendarRequest.request.mockReturnValue([
          {
            description: 'Semester1',
          }
        ]);
        const expected = [      
          {
            description: 'Semester1',
          },
        ];

        const handlers = new Handlers();
        const actual = await handlers.getSemesters();
        expect(actual).toEqual(expected);
      });
    });

How can I fix it?

Change

describe('handlers.getSemesters', async () => {

To

describe('handlers.getSemesters', () => {

And then put asynchronous code inside of it block

it('should return an array of Semesters', async () => {
  // ...
})

Async functions are syntactic sugar for returned promise chains, and Mocha's describe blocks do not support (as in waiting for resolution of) returned promises. Failing to warn about it is perhaps less helpful than it could be, but the behavior is pretty much expected under the current design.

In my case I needed to get async result for working within multiple tests. "Describe" has to be sync and we can't use nested test blocks:

describe('Not valid nested structure', () => {
    it('async parent', async () => {
        it('child', () => {})
    });
});

So my solution is:

    describe('TaskService', () => {
        let testTask;
        
        // Common async test
        it('should set test task', async () => {
            testTask = await connection.create();
            // you can add expect here
        });

        it('should update task', async () => {
            testTask.status = null;
            const updated = await connection.update(testTask);

            expect(updated.status).toEqual(null);
        });

        it('other operation with testTask above', async () => {
            // ..
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM