【问题标题】:Async await Node.js Unit Testing code using Chai and mocha使用 Chai 和 mocha 异步等待 Node.js 单元测试代码
【发布时间】:2020-02-28 06:53:50
【问题描述】:

我对 node 和 express 很陌生。并且一直在尝试用mocha、chai编写测试代码。这是源代码的一部分。

googleService.js:

const axios = require('./axios');

exports.hitGoogle = async (requestUrl, payload) => {
  let response = {};
  await axios.post(`${requestUrl}`, payload)
    .then((resp) => {
      response = resp;
      console.log(response);
    })
    .catch((err) => {
      console.error(err);
    });
  return response;
};

readGoogle.js

const googleService = require('./googleService');

exports.execute = async (data) => {
  console.log(`data ${JSON.stringify(data)}`);
  console.log(`Name ${data.name}`);
  console.log(`Salary ${data.salary}`);
  console.log(`Age ${data.age}`);
  const payload = { name: data.name, salary: data.salary, age: data.age };

  await googleService.hitGoogle('http://dummy.restapiexample.com/api/v1/create', payload)
    .then((response) => {
      if (response.status === 200 || response.status === 201) {
        console.log(response.status);
        return true;
      }
      return false;
    })
    .catch((err) => {
      console.log(err);
    });
  return true;
};

这是我的单元测试文件:

const readGoogle = require('./readGoogle');

const jmsPayload = { age: '23', name: 'test', salary: '123' };

describe('Google ', () => {
  it('POST: Google.', async () => {
     readGoogle.execute(jmsPayload).then((result) => {
     results = result;
    console.log(`Final Result : ${results.toString()}`);
  });
});

当我执行这个测试文件时,发布成功,

hitGoogle url=http://dummy.restapiexample.com/api/v1/create
hitGoogle payload=[object Object]
{ status: 200,
  statusText: 'OK',

从测试类传递到 readGoogle.js 的输入值也会在其中读取,

data {"age":"23","name":"test","salary":"123"}
Name test
Salary 123
Age 23

**But I am getting Promise as output.** 

**SO I have rendered the promised value to a normal string and getting 'true' as final output.**

还有,

  • 1)这是测试 async-await 模块的正确方法吗?

    2) 我们是否需要在此测试代码中添加任何其他内容,例如 Settimeout 还是 beforeEach 或 afterEach 块?

    3) 我们是否需要使用 Sinon 进行间谍活动或为“有效负载”添加存根 在 googleService.js 中?

谁能帮助或建议我正确的道路?

尝试了异步方式,按如下顺序依次执行测试用例,

const readGoogle = require('./readGoogle');

const jmsPayload = { age: '23', name: 'test', salary: '123' };

const common = require('./common');
const chaiHttp = common.chaiHttp;
common.chai.use(chaiHttp);

describe('Google ', () => {
  common.mocha.before((done) => {
    // Wait for the server to start up
    setTimeout(() => {
      done();
    }, 1000);
  });

  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
    setTimeout(() => {
    }, 1000);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
});

但后来我明白了,

错误:超过 2000 毫秒的超时。对于异步测试和钩子,确保调用了“done()”;如果返回一个 Promise,请确保它解决

提前致谢

【问题讨论】:

  • 你好@user1660325你解决了吗?

标签: javascript node.js unit-testing mocha.js chai


【解决方案1】:

您可以使用以下两种解决方案:

1) 回调约定:

describe('Google ', () => {
    it('POST: Google.', (done) => {
        readGoogle.execute(jmsPayload).then((result) => {
            results = result;
            console.log(`Final Result : ${results.toString()}`);
            done();
        }).catch((e) => {
            done();
        });
    });
});

2) async/await 约定

describe('Google ', () => {
  it('POST: Google.', async () => {
    const results = await readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${results.toString()}`);
  });
});

【讨论】:

  • Tran 不,它不适用于链式异步调用,我收到错误:超过 2000 毫秒的超时。对于异步测试和钩子,确保调用了“done()”;
  • 以上这些方法你都试过了吗?如果是,您可以遵循此模式。 it('不应该超时', (done) => { }).timeout(60000);
  • 你的异步函数超过了2000ms,所以会报错。因此,在每个测试用例中通过设置 .timeout(60000) 来延长超时时间。
  • yes @Hay Tran ,给了 60000 但是这段代码给出了同样的超时错误,common.mocha.before((done) => { // 等待服务器启动 setTimeout(() => { 完成(); }, 2000); });
  • 所以尽量增加到600000
猜你喜欢
  • 2018-02-13
  • 1970-01-01
  • 2021-10-03
  • 2018-11-05
  • 2017-06-20
  • 2018-02-27
  • 1970-01-01
  • 2021-09-27
  • 2018-03-06
相关资源
最近更新 更多