如何使用sinon并重新接线来模拟另一个文件中定义的常量?

编程入门 行业动态 更新时间:2024-10-10 00:25:52

如何使用sinon并重新接线来模拟另一个文件中定义的<a href=https://www.elefans.com/category/jswz/34/1769305.html style=常量?"/>

如何使用sinon并重新接线来模拟另一个文件中定义的常量?

我是JS测试的初学者,当我尝试在需要测试的文件中模拟常量值时遇到问题。

我有以下文件

// index.js
const { MultiAccounts } = require('../../some.js')

const MultiAccountInstance = new MultiAccounts();
...

const syncEvents = () => Promise.try(() => {
    // ...
    return MultiAccountInstance.all()
       .then((accounts) => // ...); // ==> it throws the exception here Cannot read property 'then' of undefined
});

module.exports = syncEvents;

所以,我想模拟MultiAccountInstance常量。我一直在尝试使用Simon和rewire,但是使用以下脚本,我已经它在这里引发了异常无法读取上面脚本中的属性'then'of undefined异常。

//index.test.js
const rewire = require('rewire');
const indexRewired = rewire('.../../index/js');

describe('testing sync events', () => {
    let fakeMultiAccountInstance, MultiAccountInstanceReverter;
    let accounts;

    beforeEach(() => {
        accounts = [{id: 1}, {id: 2}];
        fakeMultiAccountInstance = {};
        fakeMultiAccountInstance.all = () => Promise.resolve(accounts);

        MultiAccountInstanceReverter = indexRewired.__set__('MultiAccountInstance', fakeMultiAccountInstance);
    });

    afterEach(() => {
        MultiAccountInstanceReverter();
    });

    it('testing', ()=> {
        const spy = sinon.stub(fakeMultiAccountInstance, 'all');
        return indexRewired().then((resp) => {
            spy.restore();
            expect(spy).to.have.been.calledWith({someParams: true});
        });
    })
});

我该如何实现?我也尝试使用存根,但是出现了错误,即MultiAccountInstance.all不是一个函数

有点像这样

//index.test.js
const rewire = require('rewire');
const indexRewired = rewire('.../../index/js');

describe('testing sync events', () => {
    let stubMultiAccountInstance, MultiAccountInstanceReverter;
    let accounts;

    beforeEach(() => {
        accounts = [{id: 1}, {id: 2}];

        stubMultiAccountInstance= sinon.stub().returns({
          all: () => Promise.resolve(accounts), // also tried with sinon.stub().resolves(accounts)
        });

        MultiAccountInstanceReverter = indexRewired.__set__('MultiAccountInstance', stubMultiAccountInstance);
    });

    afterEach(() => {
        stubMultiAccountInstance.reset();
        MultiAccountInstanceReverter();
    });

    it('testing', ()=> {
        return indexRewired().then((resp) => {
            expect(stubMultiAccountInstance).to.have.been.calledWith({someParams: true});
        });
    })
});

你知道我在做什么错吗?

回答如下:

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

index.js

const { MultiAccounts } = require('./some.js');
const Promise = require('bluebird');

let MultiAccountInstance = new MultiAccounts();

const syncEvents = () =>
  Promise.try(() => {
    return MultiAccountInstance.all().then((accounts) => console.log(accounts));
  });

module.exports = syncEvents;

some.js

function MultiAccounts() {
  async function all() {}

  return {
    all,
  };
}

module.exports = { MultiAccounts };

index.test.js

const sinon = require('sinon');
const rewire = require('rewire');
const Promise = require('bluebird');

describe('61659908', () => {
  afterEach(() => {
    sinon.restore();
  });
  it('should pass', async () => {
    const promiseTrySpy = sinon.spy(Promise, 'try');
    const logSpy = sinon.spy(console, 'log');
    const indexRewired = rewire('./');
    const accounts = [{ id: 1 }, { id: 2 }];
    const fakeMultiAccountInstance = {
      all: sinon.stub().resolves(accounts),
    };
    indexRewired.__set__('MultiAccountInstance', fakeMultiAccountInstance);
    await indexRewired();
    sinon.assert.calledOnce(fakeMultiAccountInstance.all);
    sinon.assert.calledWith(logSpy, [{ id: 1 }, { id: 2 }]);
    sinon.assert.calledOnce(promiseTrySpy);
  });
});

带有覆盖率报告的单元测试结果:

  61659908
[ { id: 1 }, { id: 2 } ]
    ✓ should pass (54ms)


  1 passing (62ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |      80 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
 some.js  |     100 |      100 |      50 |     100 |                   
----------|---------|----------|---------|---------|-------------------

更多推荐

如何使用sinon并重新接线来模拟另一个文件中定义的常量?

本文发布于:2024-05-07 07:32:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755164.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常量   接线   如何使用   定义   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!