简体   繁体   English

如何使用 Jasmine 测试 AngularJs 全局变量

[英]How to test AngularJs global variable using Jasmine

I have a scenario where I need to test controller method using Karma Jasmine.我有一个场景,我需要使用 Karma Jasmine 测试 controller 方法。 Scenario is simple,场景很简单,

Angular code Angular代码

var globalVariable = "startEapplication";    
$scope.myMethod = function(request, response) {
                    if(globalVariable === "startEapplication" && request.customer) {

Now, instead of startEapplication I need to pass null for the negative scenario testing.现在,我需要通过 null 而不是 startEapplication 进行负面场景测试。 Basically I need to mock the global variable from Karma Jasmine.基本上我需要从 Karma Jasmine 模拟全局变量。

Is there anyway to modify the Angular global variable from Karma Jasmine.无论如何要从 Karma Jasmine 修改 Angular 全局变量。

Firstly, globalVariable is not a angular global variable and since it is declared inside controller you will not be able to access from the spec itself.首先, globalVariable 不是 angular 全局变量,由于它是在 controller 内部声明的,因此您将无法从规范本身访问。

And if you want to cover the negative scenario I used to follow below approach to test the private variable.如果你想涵盖我曾经遵循以下方法来测试私有变量的负面情况。

To test the negative scenario, you can declare one separate private object and associate it with scope.要测试负面情况,您可以声明一个单独的私有 object 并将其与 scope 关联。

Example:例子:

// Add the comment saying this should be only be accessed for unit test puropse
$scope._private_ = {
    globalVariable : "startEapplication"
}

Also you need to do the changes the way you are comparing it so that the spec will also point to same object like您还需要按照比较的方式进行更改,以便规范也指向相同的 object

if($scope._private_.globalVariable === "startEapplication")

Now you can mock this global variable inside your spec.现在你可以在你的规范中模拟这个全局变量。

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

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