如何在nodejs中对代码进行单元测试?

时间:2021-06-20 15:10:13

标签: node.js unit-testing chai sinon sinon-chai

我在下面的代码中添加了几个参数。现在我想检查这个添加是否正确执行。下面是我的代码,

"use strict";

const account = require('account');
async function main() {
  try {
    //calling an API to get data
    const mainData = await account.getData();
    const data = platformEarnings.data.items;
    const first_value =
      data[i].first_value != undefined
        ? data[i].first_value.split("@")[1]
        : "0.00";
    const second_value =
      data[i].second_value != undefined
        ? data[i].second_value.split("@")[1]
        : "0.00";
    const total_value = parseFloat(first_value) + parseFloat(second_value);
    return true;
  } catch (e) {
    logger.error("Error - [%s]", e);
    return false;
  }
}
module.exports = main;

我尝试的测试如下,

'use strict';

const { expect } = require('chai');
require('app-module-path').addPath('./src');
const axios = require('axios');
const sinon = require('sinon');
let axiosStub;

describe('Tests', () => {
  function resetSinon() {
    axiosStub.restore();
    axiosStub.reset();
    sinon.restore();
    sinon.reset();
  }

  context('when appropriate data is returned', () => {
    let result;
    before(async () => {
      axiosStub = sinon.stub(axios, 'request').callsFake((req) => {
          data = { data: {} };
          data.data = {items: [{
            first_value: '@100.00',
            second_value: '@100.00',
          }]
        };
        return data;
      });
      let testData = require('main');
      result = await testData();
    });

    after(() => {
      resetSinon();
    });

    it('should calculate correct value', async () => {
      data.data.items.forEach((items) => {
        let first_value = '0.00';
        let second_value = '0.00';
        if (items.first_value.includes('@')){
            first_value = items.first_value.split('@')[1]
        }
        if (items.second_value.includes('@')){
          second_value = items.second_value.split('@')[1]
        }
        const total_value = parseFloat(first_value) + parseFloat(second_value)
        expect(total_value).to.equal(200)
      });
    });
  });
});

在上面的测试中,我在测试中添加 first_value 和 second_value 并在下一行进行比较。但我想改变这一点,我应该能够检查实际代码中的添加是否正是我所期望的,而不仅仅是在测试用例中添加它。或者也许我写错了测试用例。让我知道如何按照我的期望进行此测试。

我是 NodeJS 中的单元测试新手,因此不胜感激。

1 个答案:

答案 0 :(得分:0)

您应该从 main 中提取要进行单元测试的业务逻辑。 像这样

"use strict";

const account = require('account');

function computeTotalValue(data){
    const first_value =
      data.first_value != undefined
        ? data.first_value.split("@")[1]
        : "0.00";
    const second_value =
      data.second_value != undefined
        ? data.second_value.split("@")[1]
        : "0.00";
    const total_value = parseFloat(first_value) + parseFloat(second_value);
    return total_value;
}

async function main() {
  try {
    //calling an API to get data
    const mainData = await account.getData();
    const data = platformEarnings.data.items;
    const total_value = computeTotalValue(data[i]);
    return true;
  } catch (e) {
    logger.error("Error - [%s]", e);
    return false;
  }
}
module.exports = { main, computeTotalValue };

既然业务逻辑在自己的功能里,就可以测试一下了:

'use strict';

const { expect } = require('chai');
require('app-module-path').addPath('./src');
const axios = require('axios');
const sinon = require('sinon');
let axiosStub;

describe('Tests', () => {
  function resetSinon() {
    axiosStub.restore();
    axiosStub.reset();
    sinon.restore();
    sinon.reset();
  }

  context('when appropriate data is returned', () => {
    let result;
    before(async () => {
      axiosStub = sinon.stub(axios, 'request').callsFake((req) => {
          data = { data: {} };
          data.data = {items: [{
            first_value: '@100.00',
            second_value: '@100.00',
          }]
        };
        return data;
      });
    });

    after(() => {
      resetSinon();
    });

    it('should calculate correct value', async () => {
      let testData = require('main');
      data.data.items.forEach((items) => {
        const total_value = testData.computeTotalValue(items);
        expect(total_value).to.equal(200)
      });
    });
  });
});