javascript - 测试方法过度指定

标签 javascript node.js

我的测试中有这个 before 函数:

before((done) => {
        const cognito = new Cognito();
        return cognito.authUser(
          '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0aaafa8ae80a4afa5eea3afad" rel="noreferrer noopener nofollow">[email protected]</a>',
          'password',
        )
      .then((res) => {
        AuthToken += res.AuthenticationResult.IdToken;
        done();
      })
      .catch((err) => {
        done(err);
      });
  });

它抛出此错误:

Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.

我认为这可能是解决办法:

before((done) => {
        const cognito = new Cognito();
        return new Promise(function(resolve) {
          cognito.authUser(
            '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f79d989f99b7939892d994989a" rel="noreferrer noopener nofollow">[email protected]</a>',
            'password',
          )
        })
      .then((res) => {
        AuthToken += res.AuthenticationResult.IdToken;
        done();
      })
      .catch((err) => {
        done(err);
      });
  });

但它给了我这个错误:

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

如何解决这个问题?

最佳答案

该错误解释了一点。

您不能同时使用回调和返回。

您有 2 个选择:

callback (the done parameter)

before((done) => {
    const cognito = new Cognito();
    cognito.authUser(
        '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e444146406e4a414b004d4143" rel="noreferrer noopener nofollow">[email protected]</a>',
        'password',
    )
    .then((res) => {
        AuthToken += res.AuthenticationResult.IdToken;
        done();
    })
    .catch((err) => done(err));
});

Return promise

before(() => {
    const cognito = new Cognito();
    return cognito.authUser(
        '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84eeebeceac4e0ebe1aae7ebe9" rel="noreferrer noopener nofollow">[email protected]</a>',
        'password',
    )
    .then((res) => {
        AuthToken += res.AuthenticationResult.IdToken;
    })
});

关于javascript - 测试方法过度指定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56275460/

相关文章:

javascript - 为什么每次都给我字符串?

javascript - 异步 waterfall : Callback already was called?

java - 优先级队列 <Double> 与优先级队列 <Node>

javascript - 将嵌套对象数据添加到表单

javascript - 从外部数据表引用表单组件 <h :form>

javascript - 为什么在 React-Native 中打开 Screen 时总是默认打开 Modal?

javascript - NodeJS fs.open 在现有文件上失败(不是路径问题)

javascript - 我不明白这个 javascript 函数调用以及它会在哪里使用

node.js - 使用 npm 安装包的目录

javascript - 在 Node-RED 的函数 Node 中使用 javascript 内置函数