使用 chai & chai-spies 在 sam 文件中用另一个函数模拟一个函数

mock a function with another function in the sam file with chai & chai-spies

我在同一个文件中有两个函数,第一个调用第二个,

我想模拟第二个并测试第一个,

async function test(data) {
  try {
    const result = await access_to_data_base(data);
    return result;
  } catch (e) {
    return e;
  }
}

async function test2(data) {
  try {
    const test = await test(data);
    // deal with the data that we retrieved 
    const result = treated_data();
    return result;
  } catch (e) {
    return e;
  }
}

export.module = {
  test, 
  test2,
}

当我想用模拟数据测试函数 test2 时,例如它将 return 一个假结果,它将 return 最终结果或捕获未异常,与 chai 和 spy

你不能模拟你的功能的原因是你的设计是耦合的,这是不好的。您的函数 test2 依赖于 test,这使得它很难测试。

为了分离它们,你可以这样做:

async function test(data) {
  try {
    const result = await access_to_data_base(data);
    return result;
  } catch (e) {
    return e;
  }
}

async function test2(results) {
  try {
    const treatedData = treated_data();
    return treatedData;
  } catch (e) {
    return e;
  }
}

export.module = {
  test, //then have some higher level function tie them together.
  test2,
}

现在这允许您单独测试函数并传入模拟数据或模拟结果。您还应该将这 2 个功能分离到单独的模块中,以遵循单一职责原则以实现更高的内聚性。