编程语言
首页 > 编程语言> > javascript – Mocha Sinon监视导入的函数

javascript – Mocha Sinon监视导入的函数

作者:互联网

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

以下是我想测试的片段:

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() {}

解决方法:

看看https://github.com/speedskater/babel-plugin-rewire

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

标签:javascript,mocha,sinon,spy
来源: https://codeday.me/bug/20190711/1430704.html