Как создать макет константы, определенной в другом файле, с помощью sinon и rewire? - PullRequest
0 голосов
/ 07 мая 2020

Я новичок в тестах 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 и перепрограммировать, но со следующим скриптом, который у меня есть , он выдает исключение здесь Cannot read property 'then' of undefined exception in the script above.

//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});
        });
    })
});

Знаете ли вы что я делаю не так?

1 Ответ

0 голосов
/ 08 мая 2020

Вот решение для модульного теста:

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 |                   
----------|---------|----------|---------|---------|-------------------
...