Mocha Sinon监视进口功能

时间:2016-06-08 03:39:06

标签: javascript mocha sinon spy

如何在不将导入的所有功能包装到对象中的情况下监视导入的函数?

关于我想如何测试的片段:

import {create} from '../../server/session/sessionFactory';
...
create = sinon.spy(create); // doesn't work, create is read-only!
...
expect(createSpy.calledOnce).to.equal(true);

它如何工作,但我不想导入所有内容:

import * as SessionFactory from '../../server/session/sessionFactory';
...
createSpy = sinon.spy(SessionFactory, 'create');
...
expect(createSpy.calledOnce).to.equal(true);

或者是在这种情况下包装的方式?

谢谢:)

为了完整起见,这里涉及的文件:

的package.json

...
"scripts": {
    "test:backend": "mocha --compilers js:babel-core/register \"test/**/*.js\"",
    "test": "parallelshell \"npm run test:backend\""
  },
...

testfile:sessionHandler.js

'use strict'

import sinon from 'sinon';
import {
  expect
} from 'chai';
import sessionHandler from '../../server/session/sessionHandler';
import * as SessionFactory from '../../server/session/sessionFactory';
// import {create} from '../../server/session/sessionFactory';

describe('sessionHandler', () => {
  describe('handleClientConnection', () => {

    let webServer, createSpy;

    beforeEach(() => {
      createSpy = sinon.spy(SessionFactory, 'create');
      // create = sinon.spy(create);
      webServer = {};
    });

    afterEach(() => {
      createSpy.restore();
      // create.restoer();
    });

    it('should create a new session', () => {
      sessionHandler.handleClientConnection(webServer);
      expect(createSpy.calledOnce).to.equal(true);
    });
  });
});

sessionHandler.js

'use strict'

import * as SessionFactory from './sessionFactory';

const SessionHandler = {
  sessions: [],

  handleClientConnection(webServer) {
    return createSession(this.sessions);
  }
}

function createSession(sessions) {
  let session = SessionFactory.create();
  sessions.push(session);
  return session;
}

export default SessionHandler;

sessionFactory.js

'use strict';

export function create() {
  return new Session();
}

function Session() {}

0 个答案:

没有答案