如何解决NodeJS测试框架中的UnhandledPromiseRejectionWarning问题

问题描述 投票:0回答:1

我在我的测试框架中使用的自定义命令是基于 Nightwatch.js. 我想通过 superagent. 这是我自定义的命令。

const superagent = require("superagent");

exports.command = function(url, header, body, callback) {
  return superagent
    .put(url)
    .send(body) // sends a JSON post body
    .set(header)
    .then(result => {
      callback(true, result);
      return this;
    })
    .catch(err => {
      if (err) {
        callback(false, err);
        return this;
      }
    });
};

而这个命令是我在测试中使用的。

return client
  .apiPut(apiUrl, header, body, function(status, result) {
    assert.isTrue(status, "response status is false");
    assert.isTrue(result.ok, "response result is NOT ok");
  })

如果PUT请求一切正常 (status == true 和成功的响应),那么一切都会好起来,测试也会结束,但是如果PUT请求不成功(status != true 和一个错误的结果)我得到以下错误信息,当前Node进程没有完成。

09:11:12 (node:103) UnhandledPromiseRejectionWarning: AssertionError: response status is false: expected false to be true
09:11:12     at /var/jenkins_home/jobs/MYJOB/workspace/testautomation/end2end-web-tests/pageobjects/MyPageView.js:59:20
09:11:12     at superagent.put.send.set.then.catch.err (/var/jenkins_home/jobs/MYJOB/workspace/testautomation/end2end-web-tests/commands/apiPut.js:14:9)
09:11:12     at <anonymous>
09:11:12     at process._tickCallback (internal/process/next_tick.js:189:7)
09:11:12 (node:103) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
09:11:12 (node:103) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

但我不知道我的自定义命令中的回调做错了什么。我应该怎么做才能解决这个问题?

javascript node.js promise nightwatch.js
1个回答
0
投票

谢谢你的帮助。现在它已经运行了。我已经替换了承诺,并将其完全替换为回调。现在它工作了:)

const superagent = require("superagent");

exports.command = function(url, header, body, callback) {
  return superagent
    .put(url)
    .send(body) // sends a JSON post body
    .set(header)
    .end((error, result) => {
      if (error) {
        callback(false, result, error);
      } else {
        callback(true, result, error);
      }
    });
};
© www.soinside.com 2019 - 2024. All rights reserved.