【问题标题】:Writing unit test case for nested function in javascript using mocha,sinon,chai使用 mocha,sinon,chai 在 javascript 中为嵌套函数编写单元测试用例
【发布时间】:2021-09-29 19:26:34
【问题描述】:

我想为 fn1() 编写单元测试用例,代码如下:

function add(a, b){
  const q = 5
  console.log(a)
  console.log(b)
  const c = a + b
  
  console.log(c)
  console.log('1')
  return c
}

function fn1(){
  let a = 5;
  let b = 6;
 let c = obj.add(a, b);
  console.log(a)
  console.log(b)
  console.log(c)
  console.log('1')
  return c;
}

我想将不同的参数传递给 fn1() 中的 add(a, b)。如何使用 mocha、sinon、chai 做到这一点?

【问题讨论】:

  • 它只是 "add(a, b)" 而不是 "obj.add(a, b)"
  • obj 在哪里定义?你为什么使用obj.add?这里的目标是什么?您面临的问题是什么?

标签: javascript node.js mocha.js sinon sinon-chai


【解决方案1】:

你可以使用sinon stub,stub add 方法并调用wrappedMethod,这是对原始方法的引用;为了强制将不同的参数传递给 add 方法。

但是你需要稍微结构化你的代码。

这里有一个简单的例子来告诉你怎么做。

我在文件 check.js 的检查对象内创建方法 add 和方法 fn1

// File: check.js
const check = {
  add: (a, b) => {
    const q = 5
    console.log('add a:', a)
    console.log('add b:', b)
    const c = a + b
    console.log('add c:', c)
    console.log('add called');
    return c
  },
  fn1: () => {
    let a = 5;
    let b = 6;
    let c = check.add(a, b);
    console.log('fn1 a:', a);
    console.log('fn1 b:', b);
    console.log('fn1 c:', c);
    console.log('fn1 called');
    return c;
  },
};

module.exports = check;

我创建了简单的测试文件:check.spec.js

// File: check.spec.js
const sinon = require('sinon');
const check = require('./check');

describe('check', () => {
  it('pass different argument to add()', () => {
    sinon.stub(check, 'add').callsFake(
      function () {
        console.log('stub add:', arguments);
        // Change the arguments here:
        arguments['0'] = 7;
        // Call write method with modified arguments.
        return check.add.wrappedMethod.apply(this, arguments);
      }
    );
    check.fn1();
  });
});

我将第一个参数 a 更改为 7。这是我在终端运行时的结果:

$ npx mocha check.spec.js


  check
stub add: [Arguments] { '0': 5, '1': 6 }
add a: 7
add b: 6
add c: 13
add called
fn1 a: 5
fn1 b: 6
fn1 c: 13
fn1 called
    ✓ pass different argument to add()


  1 passing (4ms)

【讨论】:

    猜你喜欢
    • 2019-02-03
    • 2023-04-11
    • 2018-11-05
    • 2015-03-07
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多