【问题标题】:How to unit test calculation in code in nodejs?如何在nodejs的代码中对计算进行单元测试?
【发布时间】:2021-09-04 11:49:13
【问题描述】:

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

"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 单元测试的新手,因此我们将不胜感激。

【问题讨论】:

  • 模拟 account.getData() 而不是 axios.request
  • @slideshowp2 你能解释一下吗?我使用 axios.request 因为我正在执行返回这些值的 http 请求。

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


【解决方案1】:

您应该从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)
      });
    });
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多