简体   繁体   English

Sinon 存根 - 模拟一个返回对象数组的函数

[英]Sinon stub - mocking a function which returns an array of objects

I am trying to stub the following code我正在尝试存根以下代码

async function logUpdate(client) {
  const results = await client.query(query.toParam());
  const { count, timestamp } = results.rows[0];

  await db.updateDatasourceLogs(destdb, DB.src, TABLES.src, timestamp, count);
}

This is the following code i am using to stub the above code这是我用来存根上面代码的以下代码

  fakeClient = {
      query: sinon.stub().resolves(fakeRows),
    };

   const rowData = {
      count: 1,
      timestamp: ''
   };

    fakeRows = {
      rows: sinon.stub().returns([rowData]),
    };

   fakeSequel = {
       useFlavour: sinon.stub().returns(toParam: () => false,),
   };

I am getting an error for destructuring我收到解构错误

TypeError: Cannot destructure property count of 'undefined' or 'null'.类型错误:无法解构“未定义”或“空”的属性count

at line在线

const { count, timestamp } = results.rows[0];

how to stub the above line?如何存根上面的行?

If we look at the body of your logUpdate function, we see it begins with the following two lines:如果我们查看logUpdate函数的主体,我们会看到它以以下两行开头:

const results = await client.query(query.toParam());
const { count, timestamp } = results.rows[0];

This code says:这段代码说:

  1. Await the Promise returned by the call to client.query and assign it to a variable called results .等待调用client.query返回的 Promise 并将其分配给名为results的变量。
  2. results is an Object with a property called rows which is an Array whose 0th element should be an Object with count and timestamp properties - which we destructure into local variables. results是一个对象,它有一个名为rows的属性,它是一个数组,其第 0 个元素应该是一个具有counttimestamp属性的对象 - 我们将其解构为局部变量。

This implies that the value of results looks like:这意味着结果的值如下所示:

{
  "rows": [
    {
      "count": 1
      "timestamp": "0"
    }
  ]
}

However, in our stubbing code, we have the following:但是,在我们的存根代码中,我们有以下内容:

fakeRows = {
  rows: sinon.stub().returns([rowData]),
};

Which says that fakeRows is an Object with a rows property whose value is a function that returns [rowData] .其中说fakeRows是一个具有rows属性的对象,其值是一个返回[rowData]的函数

If we were to implement this Object without sinon, it would look like:如果我们在没有 sinon 的情况下实现这个对象,它看起来像:

{
  "rows": function () {
    return [
      {
        "count": 1
        "timestamp": "0"
      }
    ];
  }
}

Notice the difference between the structure that logUpdate is expecting and what fakeRows actually provides.请注意logUpdate期望的结构与fakeRows实际提供的结构之间的区别。 Specifically, logUpdate expects results to have a rows Array , but, with our stubbed code, it has a rows Function !具体来说, logUpdate期望results有一个rows Array ,但是,使用我们的存根代码,它有一个rows函数

We can fix this simply by having fakeRows reference our rowData directly:我们可以通过让fakeRows直接引用我们的rowData来解决这个问题:

const fakeRows = {
  rows: [rowData]
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM