在jestjs中完成测试后无法记录

时间:2019-03-07 08:03:38

标签: unit-testing testing jestjs

我已经使用Jest编写了登录API的测试用例。完成一个测试服的所有五个测试后,请在日志中显示以下错误。

任何人都能说出为什么是这样以及如何解决吗?

代码:(signup.test.ts)

import request from 'supertest';
import { TYPES } from '../src/inversify.types'
import { Application } from '../src/app/Application'
import { container } from '../src/inversify.config'
import dotenv from 'dotenv'
import { RESPONSE_CODE } from '../src/utils/enums/ResponseCode'
import { RESPONSE_MESSAGES } from '../src/utils/enums/ResponseMessages'
import { UserSchema } from '../src/components/user/User';
// import jwt from 'jsonwebtoken';
var application: Application

describe("POST / - SIGNUP endpoint", () => {
    // var testusers: any;
    //This hook is executed before running all test cases, It will make application instance, make it to listen 
    // on it on port 3000 and add test document in DB
    beforeAll(async () => {
        // Make enviroment variables available throughout the application
        dotenv.config();
        // Getting application instance using iversify container
        application = container.get<Application>(TYPES.Application);
        // Initialize frontside of application
        await application.bootstrap();
        // Starting Application server on given port
        await application.listen(3000);
    });

    afterAll(
        //This hook is executed after running all test cases and delete test document in database
        async () =>{
        const res = await UserSchema.deleteMany({ Name: { $in: [ "Test User", "Test" ] } });
        // `0` if no docs matched the filter, number of docs deleted otherwise
        console.log('---------------------->>>>>>>>>>>>>>>>>>>', (res as any).deletedCount);
    }
    )

    it("Signup for user that don\'t exists", async () => {
        const response = await request(application.getServer()).post('/user/signup')
        .send({
            "Email": JSON.parse(process.env.TEST_USER).Email,
            "Name": "Test User",
            "Password": process.env.TEST_ACCOUNTS_PASSWORD
            })
            expect(response.status).toBe(RESPONSE_CODE.CREATED);
            expect(JSON.parse(response.text)).toEqual(expect.objectContaining({ 
                Message: RESPONSE_MESSAGES.ADDED_SUCESSFULLY, 
                Data: expect.objectContaining({
                    Name: 'Test User',
                    Country: '',
                    PhoneNumber: '',
                    // Password: '$2b$10$nIHLW/SA73XLHoIcND27iuODFAArOvpch6FL/eikKT78qbShAl6ry',
                    Dob: '',
                    Role: 'MEMBER',
                    IsEmailVerified: false,
                    IsBlocked: 'ACTIVE',
                    IsTokenSent: false,
                    twoFAStatus: false,
                    // _id: '5c812e2715e0711b98260fee',
                    Email: JSON.parse(process.env.TEST_USER).Email
                })
            })
            );
        console.log('*** Signup for user that don\'t exists *** response', response.text, 'response status', response.status);   
    });
    it("Signup for user that exists", async () => {
        const response = await request(application.getServer()).post('/user/signup')
        .send({
            "Email": JSON.parse(process.env.TEST_USER).Email,
            "Name": "Test User",
            "Password": process.env.TEST_ACCOUNTS_PASSWORD
            })
            expect(response.status).toBe(RESPONSE_CODE.CONFLICT);
            expect(JSON.parse(response.text)).toEqual({ 
                Message: RESPONSE_MESSAGES.ALREADY_EXISTS
            })
        console.log('*** Signup for user that don\'t exists *** response', response.text, 'response status', response.status);   
    });

});
  

测试运行一秒钟后,Jest没有退出。

     

这通常意味着有些异步操作不是   在测试中停止了。考虑使用   --detectOpenHandles来解决此问题。

     

测试完成后无法记录。你忘了等什么吗   测试中不同步?

Attempted to log "{ accepted: [ 'unverifiedtestuser@abc.com' ],
      rejected: [],
      envelopeTime: 621,
      messageTime: 867,
      messageSize: 906,
      response: '250 2.0.0 OK  1551945300 f6sm5442066wrt.87 - gsmtp',
      envelope:
       { from: 'abc@gmail.com',
         to: [ 'unverifiedtestuser@abc.com' ] },
      messageId: '<45468449-b5c8-0d86-9404-d55bb5f4g6a3@gmail.com>' }".




at CustomConsole.log (node_modules/jest-util/build/CustomConsole.js:156:10)
  at src/email/MailHandler.ts:2599:17
  at transporter.send.args (node_modules/nodemailer/lib/mailer/index.js:226:21)
  at connection.send (node_modules/nodemailer/lib/smtp-transport/index.js:247:32)
  at callback (node_modules/nodemailer/lib/smtp-connection/index.js:435:13)
  at stream._createSendStream (node_modules/nodemailer/lib/smtp-connection/index.js:458:24)
  at SMTPConnection._actionSMTPStream (node_modules/nodemailer/lib/smtp-connection/index.js:1481:20)
  at SMTPConnection._responseActions.push.str (node_modules/nodemailer/lib/smtp-connection/index.js:968:22)
  at SMTPConnection._processResponse (node_modules/nodemailer/lib/smtp-connection/index.js:764:20)
  at SMTPConnection._onData (node_modules/nodemailer/lib/smtp-connection/index.js:570:14)

3 个答案:

答案 0 :(得分:7)

发生Cannot log after tests are done时,我使用的是本机默认测试用例(见下文)。

it('renders correctly', () => {
  renderer.create(<App />);
});

显然,问题在于测试结束了,但仍然需要记录日志。因此,我尝试使测试用例中的回调异步进行,希望测试不会立即终止:

it('renders correctly', async () => {
  renderer.create(<App />);
});

它奏效了。但是,我几乎不知道内部工作是什么。

答案 1 :(得分:1)

如果您在代码中使用了异步/等待类型,那么当您在不使用async关键字的情况下调用await函数时,就会发生此错误。

就我而言,我在下面定义了这样的函数,

async getStatistics(headers) {
    ....
    ....
    return response;
}

但是我将这种方法称为getStatistics(headers)而不是await getStatistics(headers)

当我加入await时,它工作正常,问题已解决。

答案 2 :(得分:0)

我遇到了类似的问题:

Cannot log after tests are done. Did you forget to wait for something async in your test?
Attempted to log "Warning: You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. ".

这是由于缺少 static 关键字。此代码导致了问题:

class MyComponent extends React.Component<Props, State> {
  propTypes = {
    onDestroy: PropTypes.func,
  }
}

应该是:

class MyComponent extends React.Component<Props, State> {
  static propTypes = {
    onDestroy: PropTypes.func,
  }
}