简体   繁体   English

使用Mocha测试功能内的JavaScript代码

[英]Testing javascript code inside a function using mocha

Supposing I have the following function inside an external javascript file sampleFunction.js: 假设我在外部javascript文件sampleFunction.js中具有以下功能:

function mathOperation(a,b){
    var sum = a + b;
    var diff = a - b;
    var product = a * b;
}

And I would want to perform unit tests on this function using mochaJS from another separate file, say test.js. 我想使用另一个单独文件(例如test.js)中的mochaJS在此功能上执行单元测试。 In that file I want to test the mentioned function for different inputs, and test the results. 在该文件中,我想针对不同的输入测试上述功能,并测试结果。 For example, I want to check whether the sum is 30 and the difference is 10 if I pass (20,10) to the function. 例如,如果我将(20,10)传递给函数,我想检查总和是否为30,差是否为10。

So in my test file, the code would be like this:- 因此在我的测试文件中,代码将如下所示:-

var expect = chai.expect;
describe('Testing the function mathOperation()',function(){
    //test cases for checking sum, difference and product in mathOperation()
    ...
    ...
});

How do I go about writing the test cases to check the values of the sum, difference etc? 如何编写测试用例以检查总和,差等的值?

The reason why I ask the question is to know how can we test much bigger functions written in javascript which do not return anything, and to know whether we can test and compare the values of the various variables inside the function. 我问这个问题的原因是要知道我们如何测试用javascript编写的,不会返回任何内容的更大函数,以及要知道我们是否可以测试和比较函数内部各个变量的值。

how can we test much bigger functions written in javascript which do not return anything... 我们如何才能测试用JavaScript编写的更大的函数,这些函数不会返回任何内容...

Unless that function updates / changes something external then it can't be verified. 除非该功能更新/更改外部内容,否则无法对其进行验证。 The only thing you can test is that the function completed successfully. 您唯一可以测试的是功能已成功完成。

...and compare the values of the various variables inside the function ...并比较函数内部各个变量的值

You can't, and this is nothing to do with unit testing or Mocha in particular, this is just plain old JavaScript rules. 您不能,这与单元测试或Mocha无关,这只是普通的旧JavaScript规则。 Variables declared within a function are scoped to that function only, they can't be accessed externally. 在函数中声明的变量仅作用于该函数,不能从外部访问它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM