我可以通过测试用例编辑和查看代码中的全局变量

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

我使用Jest编写一些测试用例。我需要测试的JavaScript文件有一些全局变量,我想获取并设置这些全局变量的值。我试图导出全局变量并直接使用in test.js。但是,它不起作用。有一个简单的代码:

simple.js:

    var someGlobalVariable = '';
    //Basic Function with no return type
    function firstFunction() {
        someGlobalVariable = 'hello';
    }
    //Function which returns String
    function secondFunction() {
        //firstFunction();
        console.log(someGlobalVariable);
        return someGlobalVariable;
    }

    module.exports.firstFunction= firstFunction;
    module.exports.secondFunction = secondFunction;
    module.exports.someGlobalVariable = someGlobalVariable;

simple.test.js:const jstester = require('./Test');

    test('secondFunction', ()=>{
        //jstester.firstFunction();
        jstester.someGlobalVariable = 'world';
        console.log(jstester.someGlobalVariable);
        expect(jstester.secondFunction()).toMatch('world');
    });

结果是:

    FAIL  ./Test.test.js
    ✕ secondFunction (19ms)

    ● secondFunction

    expect(received).toMatch(expected)

    Expected value to match:
        "world"
    Received:
        ""

   5 |     jstester.someGlobalVariable = 'world';
   6 |     console.log(jstester.someGlobalVariable);
>  7 |     expect(jstester.secondFunction()).toMatch('world');
     |                                       ^
   8 | });
   9 |
  10 |

  at Object.toMatch (Test.test.js:7:39)

  console.log Test.test.js:6
      world

  console.log Test.js:12

  Test Suites: 1 failed, 1 total
  Tests:       1 failed, 1 total
  Snapshots:   0 total
  Time:        0.961s, estimated 1s
  Ran all test suites.

simple.js中的someGlobalVariable仍然是“。但我希望simple.test.js将值更改为”world“。

有没有办法直接改变价值?或者我必须在simple.js中添加set和get函数?

javascript jestjs
1个回答
0
投票

我不确定你的用例,但我确实有一些建议:

  1. someGlobalVariable更改为对象并直接进行变异。解决方案将是这样的:

simple.js:

var someGlobalVariable = {
  value: "hello"
};
//Basic Function with no return type
function firstFunction() {
  someGlobalVariable.value = "hello";
}
//Function which returns String
function secondFunction() {
  //firstFunction();
  console.log(someGlobalVariable.value);
  return someGlobalVariable.value;
}

module.exports.firstFunction = firstFunction;
module.exports.secondFunction = secondFunction;
module.exports.someGlobalVariable = someGlobalVariable;

simple.test.js:

const jstester = require("./simple");
test("secondFunction", () => {
  //jstester.firstFunction();
  jstester.someGlobalVariable.value = "world";
  console.log(jstester.someGlobalVariable.value);
  expect(jstester.secondFunction()).toMatch("world");
});

这是有效的,因为您没有更改对主题的引用,您只是在基础引用相同时更改属性。

  1. secondFunction收到一个变量,原始的someGlobalVariable作为默认值: function secondFunction(dependency = someGlobalVariable){// firstFunction();的console.log(someGlobalVariable); return someGlobalVariable; }

这样,您可以将任意值传递给secondFunction并测试您的特定情况。但是,这不会改变simple.js中的全局变量。

希望这个帮手!干杯:)

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