如何存根节点缓存的cache.get()?

问题描述 投票:1回答:1

我正在为使用node-cache的函数编写单元测试。在以下功能中,

  1. 我想在第一个cache.get处返回字符串>
  2. 第二个cache.get中的数组
  3. [请注意,由于它与我的问题无关,因此我从testFunction中删除了部分代码。

const NodeCache          = require('node-cache');
const cache              = new NodeCache();
...
const testFunction = () => {
  let myStringCache = cache.get('cacheName1');
  let myArrayCache = cache.get('cacheName2');

   ... Do something with caches ...

   return 'return something';
}

...
module.exports = {
   ...,
   testFunction,
   ...
}

我创建了以下测试

describe('sample test with testFunction() ', ()=>{
  let stubCache;
  let stub;
  before((done)=>{
    sandbox = sinon.createSandbox();
    stubCache = sandbox.stub(cache, 'get');
    stubCache.withArgs('cacheName1').returns('sample string');
    stubCache.withArgs('cacheName2').returns([1,2,3,4,5,6]);
    stub = proxyquire('./filelocation.js',{
      'node-cache': stubCache
    });
    done();
  });

  it('should not throw error',(done)=>{
    chai.expect(stub.testFunction()).not.to.throw;
  });
})

我正在谷歌搜索,有一些使用proxyquire存根值的部分解决方案。但看起来确实存在存根,但不是我想要的位置。它在NodeCache存根,但cache

所以我有问题:

  1. 有人知道如何将cache.get()mochachaisinon存根吗?如果是这样,请分享您的做法?
  2. 是否可以通过cache.get()的参数对不同的收益存根?

我正在为使用节点缓存的功能编写单元测试。在下面的函数中,我想在第一个缓存中返回一个字符串。在第二个缓存中获取一个数组。get请注意,我...

node.js testing mocha sinon chai
1个回答
0
投票

这里是单元测试解决方案:

© www.soinside.com 2019 - 2024. All rights reserved.