在存根函数之后它仍然调用真正的函数 [英] After stubbing function still it calls the real function

查看:35
本文介绍了在存根函数之后它仍然调用真正的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经存根了文件的内容,所以我只能运行外部函数

I have stubbed the content of file, so I can run through only outer function

file.html

<body onload ="test('file.txt')">
<body>

file.js

    const fs1 = require('fs');
    let param;
    module.export = {
         test,
         test1,
         param
    }

    function test (outputParam) {
      let fileData = test1(outputParam);
      param = fileData;
    }

    function test1(outputParam) {
       let data = fs1.readFileSync(outputParam);
       return data; 
    }

在这里,如您所见,我从 html onload 加载函数测试,然后 test1 调用并读取文件,我已存根此文件内容,如下面的测试所示

Here as you see I load function test from html onload and in turn test1 calls and reads file, I have stubbed this file content as shown in the test below

当我运行测试时,我想看到变量 param 具有文件内容值

When I run the test I want to see the variable param has the file content value

test.spec.js

    let sinon = require("sinon");
    let filejs = require('./file.js');

    it('should run only the outer function' ,function() {

    // I try to stub my function here
    sinon.stub(filejs,'test1').callsFake ((someArg) => {
      return "this is my file content";
    });

        // Now I will call my test function
        filejs.test(someArg);

    })

正如你在上面看到的,我已经存根了函数 test1,但当我运行测试时,我看到 test1 被调用并且它读取了真实的文件.

As you seen above I have stubbed function test1, still when I run the test I see test1 gets called and it reads the real file.

我正在使用 mocha ,我是存根或模拟概念的新手,非常感谢任何建议.

I am using mocha , I am new to stub or mock concepts, any suggestion is really appreciated.

推荐答案

您可能应该尝试存根 readFileSync.

You should probably try to stub readFileSync.

const fs = require('fs');

// ...

sinon.stub(fs, "readFileSync").callsFake ((someArg) => {
  return "this is my file content";
});

除此之外,我还发现您的代码存在两个问题.

Besides that, I can spot two issues with your code.

  • real readFileSync 将返回一个 Buffer 如果在没有第二个参数的情况下调用,而不是像您的存根那样的字符串.

  • The real readFileSync will return a Buffer if called without a second parameter, not a string like your stub does.

body onload 事件只存在于 DOM 内部.fs 模块仅在 Node.js 中可用.如果您在浏览器中运行您的代码,您将无法使用 fs.readFileSync.如果您在 Node 中运行它,您的 HTML 文件和 onload 事件将没有用处.

The body onload event only exists inside the DOM. The fs module is only available in Node.js. If you run your code in a browser, you won't be able to use fs.readFileSync. If you run it in Node, your HTML file and the onload event won't be useful.

这篇关于在存根函数之后它仍然调用真正的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆