Ложные зависимости, использующие синтаксис импорта ES6 - PullRequest
0 голосов
/ 28 января 2020

Я пишу модульный тест, используя Mocha и Sinon, и хочу смоделировать зависимость, которая использует стиль ES6 import. Ниже я включил упрощенную версию того, что я пытаюсь сделать, и подходы, которые я попробовал.

Когда я проводил онлайн-исследования, сначала я читал, что Sinon не может издеваться над модулями ES6. Однако в других местах я читал, что это можно сделать с помощью import * as syntax. Я нашел несколько примеров, которые я пытался использовать; однако до сих пор они не работали.

Я также просмотрел документацию для других библиотек, таких как proxyquire и rewire. Тем не менее, они, похоже, ориентированы на стиль Node require s, а не на стиль ES6 import s.

. Существует ли общепринятый способ подхода к зависимостям, использующим import?

* 1013? * Упрощенная версия того, что я пробовал:

зависимость. js

export function foo {
  return {
    bar: () => console.log('In real bar')
  };
};

unitUnderTest. js

import { foo } from './dependency.js';

export const exportedFunction = () => foo.bar();

testFile. js

import sinon from 'sinon';
import * as dependency from './dependency.js';
import { exportedFunction } from './unitUnderTest';

describe(`Things that I've tried`, () => {
  it('Stub dependency', () => {
    let stub;
    before(() => {
      stub = sinon.stub(dependency)
        .returns({
          foo: () => ({
            bar: () => console.log('In mocked bar')
          })
        });
    });

    exportedFunction();
  });

  it('Stub dependency.foo', () => {
    let stub;
    before(() => {
      stub = sinon.stub(dependency, 'foo')
        .returns({
          bar: () => console.log('In mocked bar')
        });
    });

    exportedFunction();
  });

  it('Stub dependency.foo directly', () => {
    let stub;
    before(() => {
      stub = sinon.stub(dependency.foo)
        .returns({
          bar: () => console.log('In mocked bar')
        });
    });

    exportedFunction();
  });

  describe(`Things that I've tried using default`, () => {
    it('Stub dependency.default', () => {
      let stub;
      before(() => {
        stub = sinon.stub(dependency, 'default')
          .returns({
            foo: () => {
              bar: () => console.log('In mocked bar')
            }
          })
      });

      exportedFunction();
    });

    it('Stub dependency.default.foo', () => {
      let stub;
      before(() => {
        stub = sinon.stub(dependency.default.foo, 'bar', () => console.log('In mocked bar'));
      });

      exportedFunction();
    });

    it('Mock dependency.default.foo', () => {
      let stub;
      before(() => {
        stub = sinon.mock(depencency.default.foo)
          .expects('bar')
          .once();
      })

      exportedFunction();
      dependency.foo.bar.verify();  // Throws an error, cannon call verify of undefined
    });
  });
});
...