Подтвердить что ты не робот

Очистка синусоидов легко

Есть ли способ легко reset всех синус-шпионов mocks и stubs, которые будут работать чисто с моккой перед каждым блоком.

Я вижу, что песочница - это вариант, но я не вижу, как вы можете использовать песочницу для этого

beforeEach ->
  sinon.stub some, 'method'
  sinon.stub some, 'mother'

afterEach ->
  # I want to avoid these lines
  some.method.restore()
  some.other.restore()

it 'should call a some method and not other', ->
  some.method()
  assert.called some.method
4b9b3361

Ответ 1

Sinon предоставляет эту функциональность с помощью Песочницы, которые можно использовать несколькими способами:

// manually create and restore the sandbox
var sandbox;
beforeEach(function () {
    sandbox = sinon.sandbox.create();
});

afterEach(function () {
    sandbox.restore();
});

it('should restore all mocks stubs and spies between tests', function() {
    sandbox.stub(some, 'method'); // note the use of "sandbox"
}

или

// wrap your test function in sinon.test()
it("should automatically restore all mocks stubs and spies", sinon.test(function() {
    this.stub(some, 'method'); // note the use of "this"
}));

Ответ 2

Вы можете использовать sinon.collection, как показано в этом блоге (датированном мая 2010 г.) автором библиотеки синонов.

Изменен sinon.collection api, и его можно использовать следующим образом:

beforeEach(function () {
  fakes = sinon.collection;
});

afterEach(function () {
  fakes.restore();
});

it('should restore all mocks stubs and spies between tests', function() {
  stub = fakes.stub(window, 'someFunction');
}

Ответ 3

Обновление для ответа @keithjgrant.

Начиная с версии v2.0.0, метод sinon.test был перенесен в отдельный sinon-test. Чтобы пройти старые тесты, вам необходимо настроить эту дополнительную зависимость в каждом тесте:

var sinonTest = require('sinon-test');
sinon.test = sinonTest.configureTest(sinon);

В качестве альтернативы вы можете обойтись без sinon-test и использовать песочницы:

var sandbox = sinon.sandbox.create();

afterEach(function () {
    sandbox.restore();
});

it('should restore all mocks stubs and spies between tests', function() {
    sandbox.stub(some, 'method'); // note the use of "sandbox"
} 

Ответ 4

Обратите внимание, что при использовании qunit вместо mocha вам необходимо обернуть их в модуль, например.

module("module name"
{
    //For QUnit2 use
    beforeEach: function() {
    //For QUnit1 use
    setup: function () {
      fakes = sinon.collection;
    },

    //For QUnit2 use
    afterEach: function() {
    //For QUnit1 use
    teardown: function () {
      fakes.restore();
    }
});

test("should restore all mocks stubs and spies between tests", function() {
      stub = fakes.stub(window, 'someFunction');
    }
);

Ответ 5

Если вам нужна настройка, которая всегда будет иметь sinon reset для всех тестов:

в helper.js:

import sinon from 'sinon'

var sandbox;

beforeEach(function() {
    this.sinon = sandbox = sinon.sandbox.create();
});

afterEach(function() {
    sandbox.restore();
});

Затем в вашем тесте:

it("some test", function() {
    this.sinon.stub(obj, 'hi').returns(null)
})

Ответ 6

restore() просто восстанавливает поведение заштрихованной функциональности, но не reset состояние заглушек. Вам придется либо обернуть ваши тесты с помощью sinon.test, либо использовать this.stub или индивидуально вызвать reset() на заглушки