javascript - 类型错误 : Cannot read property 'user_mainValue' of undefined

标签 javascript jquery angularjs jasmine karma-jasmine

更新2

hey, 



 I moved the grid value in a new mthod carSource so the previous error I removed but right now I am getting another error,
    - is there any way I can spy on _dataSource or mock the value to pass the test cases.

     can you tell me how to fix it

**TypeError: Cannot read property 'length' of undefined**

更新代码

    public carSource():any{
      let car = $('#laptopMousesGrid').data('kendoGrid');
      return  grid.dataSource;
    }

  playing(evt, dropValue, values) {
      let todayDate = this.todayDate();
      //et car = $('#laptopMousesGrid').data('kendoGrid');
      //let _dataSource = car.dataSource;

          let _dataSource =this.carSource();

      let pageSize = _dataSource.pageSize();
      if(_dataSource) {

         console.log("playing--->");
      console.log("_dataSource--->" + JSON.stringify(_dataSource));
      console.log("_dataSource._data--->" + _dataSource._data);

        let carLength = _dataSource._data.length;
      }
      let filename;
      let mainValue = this.spaceService.getSeesionStorageValue();
      console.log("playing mainValue----> " + mainValue);
      if (mainValue) {
        this.userStem = mainValue.user_mainValue.SSO[0];
        this.loggedUserName = mainValue.user_mainValue.DisplayName[0];
      }
  }

输出 日志:'播放--->' 日志:'_dataSource--->{“_isScalar”:true,“值”:[{“carsId”:“100”,“carsName”:“uuiiuui”,“carsType”:“TITLE”,“carsData”:“YWZjYXJlZ2Vyamh2dmFyZWdoYnZi","笔记":"","notesId":"100","鱼":"100","url":"ioioioiooi","日期":"ioioi","addedByName":"Kamal", “用户ID”:“6765676565”,“操作类型”:“创建”},{“carsId”:“101”,“carsName”:“example.pdf”,“carsType”:“标题”,“carsData”:“约翰","notes":"","notesId":"101","fish":"101","url":"ioioioiooi","日期":"ioioi","addedByName":"Kamal","userID":"6765676565","operationType":"create"},{"carsId":"101","carsName":"example.ppt","carsType":"TITLE","carsData":"john","notes":"","notesId":"101","fish":"101","url":"ioioioiooi","日期":"ioioi","addedByName":"Kamal","userID ":"6765676565","操作类型":"创建"}],"调度程序":null}' 日志:'_dataSource._data--->未定义' Chrome 61.0.3163 (Windows 10 0.0.0) Jasmine 单元测试:添加失败 [0]类型错误:无法读取未定义的属性“长度” Chrome 61.0.3163(Windows 10 0.0.0):执行了 69 中的 1 个(1 个失败)(跳过了 68 个)错误(0.56 秒/0.422 秒)

更新

嘿,我做了进一步的研究,问题出在这一行let car = $('#laptopMousesGrid').data('kendoGrid');

当我尝试打印汽车时,我得到了未定义的信息,是否可以模拟汽车或 spy 的值,以便我们可以设置一些值并通过测试用例...我做了一些研究,但不确定如何继续

我的应用程序通过以下代码行运行良好

let mainValue=this.spaceService.getSeesionStorageValue();

我可以在浏览器中看到 mainValue 的值,就像我的测试用例一样。提供下面的 mainValue 结果

acr:{values: Array(1)}
amr:["ext"]
cid:"7823459-78237832387278-237823873278"
client_id:"7823459-78237832387278-237823873278"
email:"parrot.tiger.com"
scope:["openid"]
sub:"3623673267-278782378-23872872378-2378327832"
user_mainValue:{BusinessSegment:["Operations & Technical Services"], DisplayName:["pen"], Title: ["Developer"], SSO:["bndsbsbnsd"]}
zid:"6fc3c2b8-f6b4-4376-824f-9c93dfcc19a3"

我看不到。

我在测试用例日志中收到未定义的错误:

'playing mainValue----> undefined'.

我需要将 spy 添加到该值中吗?

  • 我也对 spy 感到困惑。

你能告诉我如何解决这个问题吗?

[0] 23 09 2017 22:28:36.720:DEBUG [web-server]: serving (cached): C://app/components/laptops/jumping-l    LOG: '**playing mainValue----> undefined'**
[0] Chrome 60.0.3112 (Windows 10 0.0.0): Executed 17 of 34 (1 FAILED) (0 secs / 3.434 secs)
[0] 23 09 2017 22:28:36.824:DEBUG [middleware:source-files]: Requesting /app/components/laptops/swimming.html /
[0] 23 09 2017 22:28:36.824:DEBUG [middleware:source-files]: Fetching /app/components/laptops/swimming.html
[0] 23 09 2017 22:28:36.832:DEBUG [proxy]: proxying request - /app/components/laptops/swimming.html to localhost:9876
[0] 23 09 2017 22:28:36.832:DEBUG [middleware:source-files]: Requesting /base/app/components/shared/progress/progress-circle.html /
[0] 23 09 2017 22:28:36.832:DEBUG [middleware:source-files]: Fetching C://app/components/shared/progress/progress-circle.html
[0] 23 09 2017 22:28:36.832:DEBUG [middleware:source-files]: Requesting /app/components/laptops/jumping-left-slider.html /
[0] 23 09 2017 22:28:36.832:DEBUG [middleware:source-files]: Fetching /app/components/laptops/jumping-left-slider.html
[0] 23 09 2017 22:28:36.836:DEBUG [web-server]: serving (cached): C://app/components/shared/progress/progress-circle.html
    Chrome 60.0.3112 (Windows 10 0.0.0) Jasmine Unit Tests: parrot-Manage-Mouses Add Hiding Mouse FAILED
**[0]     TypeError: Cannot read property 'user_mainValue' of undefined**
[0] Chrome 60.0.3112 (Windows 10 0.0.0): Executed 18 of 34 (2 FAILED) (0 secs / 3.562 secs)

实际代码

playing(evt, dropValue, values) {
  let todayDate = this.todayDate();
  let car = $('#laptopMousesGrid').data('kendoGrid');
  let _dataSource = car.dataSource;
  let pageSize = _dataSource.pageSize();
  let carLength = _dataSource._data.length;
  let filename;
  let mainValue = this.spaceService.getSeesionStorageValue();
  console.log("playing mainValue----> " + mainValue);
  if (mainValue) {
    this.userStem = mainValue.user_mainValue.SSO[0];
    this.loggedUserName = mainValue.user_mainValue.DisplayName[0];
  }

测试用例

<!-- language-all: lang-or-tag-here -->

it('Add Hiding Mouse', (done) => {
  let callFirstTime: boolean = true;
  let url = spyOn(rainbow.HidingMouses.spaceService, 'getResponse').and.
  callFake(() => {
    if (callFirstTime) {
      callFirstTime = false; // Invoked by detectChanges() 
      return Observable.of([{
        "starsStem": "100",
        "starsName": "/assets/js/actualairings.json",
        "starsType": "TITLE",
        "starsData": "YWZjYXJlZ2Vyamh2dmFyZWdoYnZi",
        "jersey": "",
        "jerseyStem": "100",
        "DocRing": "100",
        "url": "/upload",
        "date": "06/27/2017",
        "addedByName": "Kamal",
        "userRing": "",
        "operationType": "create"
      }]);
    }
  });
  spyOn(rainbow.HidingMouses.carkendo, 'enableSaveMouse').and.returnValue(
    null);
  rainbow.HidingMouses.fileSelect = "text.txt";
  let values = {
    "url": "laptops/v1/stars/current",
    "columns": [],
    "title": "sky",
    "excelFileName": "ViewAiringsExport",
    "mainStem": current
  };

  rainbow.HidingMouses.playing('', '', values);
  fixture.whenStable().then(() => {
    done();
    expect(rainbow.HidingMouses._dataSource._data.length).toEqual(3);
  });
});

最佳答案

我假设 this.spaceService.getSeesionStorageValue(); 实际上是从浏览器 session 存储中读取某些内容,这些内容在测试时尚未添加到测试浏览器的 sessionStorage 中。无论哪种方式,您都应该将该服务模拟为单元测试的外部依赖项。 Jasmine spy 就可以了。

像这样将 spaceService 注入(inject)到您的测试中

var spaceService;
beforeEach(inject(function(_spaceService_){
spaceService = _spaceService_
));

现在模拟服务上的方法

spyOn(spaceService, 'getSeesionStorageValue');
spaceService.getSeesionStorageValue.andReturn('here is the main value');

现在您应该收到一条日志,内容为'playing mainValue---->here is the main value'

关于javascript - 类型错误 : Cannot read property 'user_mainValue' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46386120/

相关文章:

html - 当一个单元格悬停在上面时,有没有一种方法可以将一个类添加到 ng-repeat 中的一行?

javascript - 手动请求模块与使用 browserify 动态调用模块有何不同?

javascript - AngularJS 中的动态布局

javascript - 货币验证

javascript - 如何更改 "progress[value]::-webkit-progress-value"属性的颜色?

javascript - Joi 验证 : multiple validation error messages for single field

javascript - 如何删除元素并在 <ul> 列表中的第 n 个 <li> 之后添加新元素?

javascript - 检查更改的文本

javascript - 拆分列表的 jQuery 函数

javascript - "Fail Render"Javascript 文件和 Css