можем ли мы заменить несколько методов одного и того же ресурса в sinun.stub

#javascript #chai #sinon

Вопрос:

Можем ли мы заменить несколько методов одного и того же ресурса в одном тестовом примере

 it('should render', () => {
    // first replace
    sinon.stub(DBInstance.getCollection(), 'find').returns({});

    //second replace
    sinon.stub(DBInstance.getCollection(), 'findOne').returns({});
    ...
    ...
});
 

Комментарии:

1. Чего ты ожидаешь? Что ты получил?

Ответ №1:

Да, ты можешь. Вы можете сначала сохранить ресурс и заглушить его, или вы можете использовать прототип ресурса, чтобы заглушить его.

Это простой проверочный код только для примера, потому что я не знаю, какой модуль вы используете.

 // File: check.js
class Resource {
  find() { console.log('real find') }
  findOne() { console.log('real findOne') }
};

const check = {
  getCollection: () => {
    return new Resource();
  },
};

module.exports = { check, Resource };
 

Это тестовый файл, показывающий, что вы можете заменить несколько методов одного и того же ресурса.

 // File: check.spec.js
const sinon = require('sinon');
const { expect } = require('chai');
const { check, Resource } = require('./check');

describe('stub check', () => {
  it('using stored resource', () => {
    // Store the resource first.
    const collection = check.getCollection();
    // Using the stored resource to stub it.
    sinon.stub(collection, 'find').returns({});
    sinon.stub(collection, 'findOne').returns({});
    expect(collection.find()).to.deep.equal({});
    expect(collection.findOne()).to.deep.equal({});
    sinon.restore();
  });

  it('using prototype resource', () => {
    // Using the prototype resource.
    sinon.stub(Resource.prototype, 'find').returns({});
    sinon.stub(Resource.prototype, 'findOne').returns({});
    expect(check.getCollection().find()).to.deep.equal({});
    expect(check.getCollection().findOne()).to.deep.equal({});
    sinon.restore();
  });
});
 

Результат, когда я запускаю его из терминала:

 $ npx mocha check.spec.js 


  stub check
    ✓ using stored resource
    ✓ using prototype resource


  2 passing (4ms)
 

Не вызывается ни один реальный метод.