如何模拟函数后如何检查属性值:断言错误,摩卡

问题描述 投票:0回答:1

根据有问题的建议enter link description here,我模拟了readFileSync并模拟了我的外部函数,现在我想验证变量值是否设置为预期值

file.js

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

    function test (outputParam) {
     param = fs1.readFileSync(outputParam);
    }

我已将这个readFileSync存入存根,并且它返回指定的文件内容,如下面的测试所示

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

test.spec.js

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


    it('should run only the outer function and test if variable param is set to `this is my file content` ' ,function() {

     let someArg ="file.xml";

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

      var mock = sinon.mock(filejs);
      mock.expects('test').withArgs(someArg);
      expect(filejs.param).to.equal('this is my file content');

  })

从file.js,如您所见,属性param从“ readFileSync”获取值,该值被存根以返回值

我运行测试时

expect(filejs.param).to.equal('这是我的文件内容');

AssertionError:预期未定义等于'这是我的文件内容'

javascript node.js unit-testing mocha sinon
1个回答
0
投票

注意module.exports的正确拼写-而不是module.export

在您的file.js中,变量param未初始化,因此它将获得值undefined,并且也将使用该值导出。如果以后修改param,则导出的值不会更改。导出仅将属性绑定到值,而不绑定到变量。实际上,您甚至不需要局部变量。要动态更改导出的值,至少在Node中,只需在module.exports上重新分配属性即可。

const fs1 = require('fs');

module.exports = {
     test
}

function test (outputParam) {
    module.exports.param = fs1.readFileSync(outputParam);
}

至于您的test.spec.js,您已经非常接近可以使用它了。对不应该在集线器下调用的方法进行存根后,只需调用test函数,并传递实参即可。那里不需要模拟。

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


it('should run only the outer function and test if variable param is set to `this is my file content` ' ,function() {

 let someArg ="file.xml";

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

  filejs.test(someArg);

  expect(filejs.param).to.equal('this is my file content');

});

© www.soinside.com 2019 - 2024. All rights reserved.