gpt4 book ai didi

javascript - Mocha Sinon 监视导入函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:41:26 25 4
gpt4 key购买 nike

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

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

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);

或者在这种情况下要走什么路?

谢谢:)

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

包.json

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

测试文件: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 监视导入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37692820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com