Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Sinon存根不适用于导出的函数_Javascript_Sinon_Sinon Chai - Fatal编程技术网

Javascript Sinon存根不适用于导出的函数

Javascript Sinon存根不适用于导出的函数,javascript,sinon,sinon-chai,Javascript,Sinon,Sinon Chai,Sinon似乎没有从导入的文件中删除方法。这与导出常量有关吗 我在console.log中看到“已接收原始消息” Main.js import * as otherActions from 'filters/actions/Other.actions'; describe('filter actions', () => { it('should log STUBBED MESSAGE', () => { sinon.stub(otherActions,

Sinon似乎没有从导入的文件中删除方法。这与导出常量有关吗

我在console.log中看到“已接收原始消息”

Main.js

import * as otherActions from 'filters/actions/Other.actions';

describe('filter actions', () => {

    it('should log STUBBED MESSAGE', () => {   
      sinon.stub(otherActions, 'logMessage').callsFake(m => console.log('STUBBED Message'));
      const compiled = otherActions.doSomethingAndLogMessage(5, 5);
      compiled(message => console.log(`RECEIVED ${message}`), () => {});
    });

});
export const logMessage = () => console.log("ORIGINAL MESSAGE");

export const doSomethingAndLogMessage = (categoryId, size) => (dispatch, getState) => {
  dispatch(logMessage());
};
Other.actions.js

import * as otherActions from 'filters/actions/Other.actions';

describe('filter actions', () => {

    it('should log STUBBED MESSAGE', () => {   
      sinon.stub(otherActions, 'logMessage').callsFake(m => console.log('STUBBED Message'));
      const compiled = otherActions.doSomethingAndLogMessage(5, 5);
      compiled(message => console.log(`RECEIVED ${message}`), () => {});
    });

});
export const logMessage = () => console.log("ORIGINAL MESSAGE");

export const doSomethingAndLogMessage = (categoryId, size) => (dispatch, getState) => {
  dispatch(logMessage());
};

出现此问题的原因是,当在模块上下文中引用时,您正在导出模块中存根函数。当从模块内部引用它时,您不是存根。有很多方法可以解决这个问题,但我认为所有这些都需要您稍微更改一下生产代码

一项建议是:

Other.actions.js

export const logger = { message: () => console.log("ORIGINAL MESSAGE") };
Main.js

import * as otherActions from 'filters/actions/Other.actions';

...
sinon.stub(otherActions.logger, 'message')
  .callsFake(m => console.log('STUBBED Message'));
重要的是,您要在测试模块可用的上下文中创建存根


另一个一般性意见是,通常情况下,您不希望在正在测试的模块中模拟或存根函数或方法。通常,单元测试单元指的是一个模块。因此,如果您发现需要在正在测试的同一模块中删除某些内容,那么我建议您的模块边界不正确。

您使用的是哪一版本的sinon?我使用的是5.0.10版