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

ybzsozfc  于 2022-12-08  发布在  Jest
关注(0)|答案(8)|浏览(187)

我已经用jest写了一个登录API的测试用例。在完成了一个测试套的所有五个测试后,jest给予我下面的错误日志。
有谁能说出为什么会这样,以及如何解决它?

代码:(注册.测试.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运行Jest以解决此问题。
测试完成后无法记录。您是否忘记等待测试中的异步内容?

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)
k75qkfdt

k75qkfdt1#

Cannot log after tests are done发生时,我正在使用react-native默认测试用例(见下文)。

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

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

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

而且它起作用了。然而,我对内在的工作是什么几乎一无所知。

mwngjboj

mwngjboj2#

如果您在代码中使用async/await类型,则在调用不带await关键字的async函数时可能会发生此错误。
在我的例子中,我定义了一个如下所示的函数,

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

但是我已经像getStatistics(headers)而不是await getStatistics(headers)那样调用了这个方法。
当我包含await时,它工作正常,问题解决了。

sbdsn5lh

sbdsn5lh3#

对我来说,我需要在expect()调用之前添加一个await来阻止此错误(并在test()回调函数之前添加一个async)。
还导致并修复了Jest未检测到代码行上的覆盖率而引发的错误!

test("expect error to be thrown for incorrect request", async () => {
  await expect(
  // ^ added this
    async () => await getData("i-made-this-up")
  ).rejects.toThrow(
    "[API] Not recognised: i-made-this-up"
  );
});

getData()返回Axios调用,在这种情况下,catch捕获错误并重新抛出。

const getData = async (id) => {
  return await axios
    .get(`https://api.com/some/path?id=${id}`)
    .then((response) => response.data)
    .catch((error) => {
      if (error?.response?.data?.message) {
        console.error(error) // Triggered the error
        throw new Error("[API] " + error.response.data.message);
      }

      throw error;
    });
};
qojgxg4l

qojgxg4l4#

这种情况发生在我身上,因为我有一个无限循环while (true)。在我的例子中,我能够添加一个方法,根据用户输入设置循环的值,而不是默认为true。

2w3kk1z5

2w3kk1z55#

在我使用nodejs + jest + supertest的情况下,问题是当我将import app from "./app"添加到测试文件以使用supertest(request(app))执行一些操作时,我实际上使用了app.listen()进行导入,因为当我导出app时,export也会考虑app.listen(),但我们在测试中不需要app.listen(),因此会引发错误
“无法在测试完成后记录。您是否忘记在测试中等候异步的项目?”

所有内容都在一个文件中(这就是问题所在!)

const app = express();

app.use(express.json());

// ROUTES
app.get("/api", (req, res) => {
  res.json({ message: "Welcome to Blog API!" });
});

app.use("/api/users", usersRoutes);
app.use("/api/blogs", blogsRouter);

// The server will start only if the connection to database is established
mongoose
  .connect(process.env.MONGO_URI!)
  .then(() => {
    console.log("MongoDB est connecté");

    const port = process.env.PORT || 4000;
    app.listen(port, () => console.log(`The server is running on port: ${port}`));
  })
  .catch(err => {
    console.log(err);
  });

export default app;

为了解决此问题,我创建了两个单独的文件夹:
// 1)应用程序ts

在那里我把我的const app = express(),路线等所有东西和导出应用程序

dotenv.config();

const app = express();

app.use(express.json());

// ROUTES
app.get("/api", (req, res) => {
  res.json({ message: "Welcome to Blog API!" });
});

app.use("/api/users", usersRoutes);
app.use("/api/blogs", blogsRouter);

export default app;

// 2)索引.ts

在这里我放置app.listen() and mongoose.connection()并导入app

*import mongoose from "mongoose";
import app from "./app";

// The server will start only if the connection to database is established

mongoose
  .connect(process.env.MONGO_URI!)
  .then(() => {
    console.log("MongoDB est connecté");

    const port = process.env.PORT || 4000;
    app.listen(port, () => console.log(`The server is running on port: ${port}`));
  })
  .catch(err => {
    console.log(err);
  });*
eivgtgni

eivgtgni6#

在我的例子中,这个错误是由于Redis的异步连接仍然在线引起的。只要添加afterall方法退出Redis,就可以再次看到日志。
使用 typescript 4.4.2:

test("My Test", done => {
    let redisUtil: RedisUtil = new RedisUtil();
    let redisClient: Redis = redisUtil.redis_client();
    done();
});

afterAll(() => {
    redisClient.quit();
});
f5emj3cl

f5emj3cl7#

我用env变量解决了这个问题:

if (process.env.NODE_ENV !== 'test') {
  db.init().then(() => {
    app.listen(PORT, () => {
      console.log('API lista por el puerto ', PORT)
    })
  }).catch((err) => {
    console.error(err)
    process.exit(1)
  })
} else {
  module.export = app
}
vmdwslir

vmdwslir8#

我也遇到过类似的问题:

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,
  }
}

相关问题