小编kar*_*sys的帖子

如何在 Angular 组件中模拟服务功能进行单元测试

我正在为 angular 应用程序编写单元测试,我正在测试服务函数是否返回一个值。

组件.spec.ts

import {TopToolBarService} from '../../top-toolbar/top-toolbar.service';

beforeEach(async(() => {
   TestBed.configureTestingModule ({
   declarations: [ UsersListComponent],
   providers: [TopToolBarService],//tried mocking service here,still test failed
   schemas:[CUSTOM_ELEMENTS_SCHEMA]
 })
  .compileComponents();
}));



beforeEach(() => {
    fixture = TestBed.createComponent(UserListComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });



  it('should return data from service function', async(() => {
    let mockTopToolBarService: jasmine.SpyObj<TopToolBarService>;
    mockTopToolBarService = jasmine.createSpyObj('TopToolBarService', ['getCustomer']);
    mockTopToolBarService.getCustomer.and.returnValue("king");
    fixture.detectChanges();
    expect(component.bDefine).toBe(true); //fails
  }))

Run Code Online (Sandbox Code Playgroud)

组件.ts

bDefine = false;
ngOnInit() {
 let customer = this.topToolBarService.getCustomer();
 if (customer == null) {
   bDefine = false;
 } else { …
Run Code Online (Sandbox Code Playgroud)

unit-testing typescript angular

18
推荐指数
3
解决办法
5万
查看次数

Angular 单元测试:警告:'导航在 Angular 区域外触发,您是否忘记调用'ngZone.run()'?'

我正在为从数据库中删除帐户的 Angular 应用程序编写单元测试。为此,我单击删除按钮。然后在 .ts 文件上调用函数。这将通过调用 API 删除帐户。

我想编写单元测试以查看是否使用 HttpTestingModule 调用此 API,它确实如此,但在帐户删除后的代码中,我使用 router.navigate 导航到不同的页面。当代码命中时,它会抱怨警告:“导航在 Angular 区域外触发,您是否忘记调用 'ngZone.run()'?”

ERROR: 'Unhandled Promise rejection:', 'Cannot match any routes. URL Segment: 'accountsList'', '; Zone:', 'ProxyZone', '; Task:', 'Promise.then', '; Value:', Error: Cannot match any routes. URL Segment: 'accountsList'
Error: Cannot match any routes. URL Segment: 'accountsList'
    at ApplyRedirects.noMatchError (./node_modules/@angular/router/fesm5/router.js?:1455:16)
    at CatchSubscriber.eval [as selector] (./node_modules/@angular/router/fesm5/router.js?:1436:29)
    at CatchSubscriber.error (./node_modules/rxjs/_esm5/internal/operators/catchError.js?:40:31)
    at MapSubscriber.Subscriber._error (./node_modules/rxjs/_esm5/internal/Subscriber.js?:89:26)
    at MapSubscriber.Subscriber.error (./node_modules/rxjs/_esm5/internal/Subscriber.js?:69:18)
    at MapSubscriber.Subscriber._error (./node_modules/rxjs/_esm5/internal/Subscriber.js?:89:26)
    at MapSubscriber.Subscriber.error (./node_modules/rxjs/_esm5/internal/Subscriber.js?:69:18)
    at MapSubscriber.Subscriber._error (./node_modules/rxjs/_esm5/internal/Subscriber.js?:89:26)
    at MapSubscriber.Subscriber.error (./node_modules/rxjs/_esm5/internal/Subscriber.js?:69:18) …
Run Code Online (Sandbox Code Playgroud)

unit-testing typescript angular

6
推荐指数
1
解决办法
5547
查看次数

使用 rxjs 运算符是否可以获得倒数第二个值

这是使用rxjs运算符的示例代码,我想打印/获取倒数第二个值。

打字稿

import { from } from 'rxjs';
import { map, last } from 'rxjs/operators';

//emit (1,2,3,4,5)
const source = from([1, 2, 3, 4, 5]);
//add 10 to each value
const example = source.pipe(map(val => val + 10)).pipe(last());
//output: 11,12,13,14,15
const subscribe = example.subscribe(val => console.log(val));

Run Code Online (Sandbox Code Playgroud)

目前它可以打印,15但我希望它改为打印14

rxjs typescript angular

6
推荐指数
1
解决办法
3546
查看次数

如何从现有的 Angular cli 项目中删除所有规范文件

我目前正在使用 angular cli 项目。我看到为每个组件、服务生成的规范文件,我想从这个现有项目中删除所有这些规范文件。

angular

5
推荐指数
1
解决办法
4042
查看次数

如何在角度单元测试中访问 .css 文件中存在的样式

我正在为角度应用程序运行单元测试,我尝试从单元测试内的 .css 访问样式。我会让你知道我尝试了什么

 component.listedIps.length=0;
 fixture.detectChanges();

 let whitelistipsdiv=fixture.debugElement.query(By.css('.divAllAllowedIPs'));

 //unit test for style, test for  background-color to be green
 expect(whitelistipsdiv.nativeElement.style.backgroundColor).toEqual('green');// to be darkgreen, here it is null
Run Code Online (Sandbox Code Playgroud)

.css 文件

.divAllAllowedIPs {
  background-color: green;
}
Run Code Online (Sandbox Code Playgroud)

css unit-testing typescript karma-jasmine angular

4
推荐指数
1
解决办法
7191
查看次数

如何将值赋予jquery点击功能

我想将元素的 id 值传递给 jquery 单击函数。

这是代码片段

function maintest() {
   var buttonElem = $('<button>').attr({"id" : "buttonMain" }).css ({"cursor" :"pointer"}).text("Click me!").click(function() {
      buttonClicked ();
   });
   
   $("#mainDiv").append(buttonElem);
  }
   
  
  function  buttonClicked () {
    alert("button clicked");
  }
Run Code Online (Sandbox Code Playgroud)
<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body onload ="maintest()">
  <div id="mainDiv"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我想将 id 值“buttonMain”传递给“buttonClicked”函数,

这是我试过的


function maintest() {
   var buttonElem = $('<button>').attr({"id" : "buttonMain" }).css ({"cursor" :"pointer"}).text("Click me!").click(function(this.id) {
      buttonClicked (this.id);
   });

   $("#mainDiv").append(buttonElem);
  }


  function  buttonClicked (elem) {
    alert("button clicked");
    alert("passed elem id value"+ elem);
  }
Run Code Online (Sandbox Code Playgroud)

html javascript css jquery

4
推荐指数
1
解决办法
113
查看次数

Electron 应用程序大小对于 Linux 为 450 mb,对于 Windows 为 238 mb,如何相对于 Visual Studio 代码减少它

我已经构建了一个电子应用程序并使用电子打包器对其进行了打包。我制作了 238MB 的 Windows 捆绑包,Linux 版本的捆绑包为 450 MB。我将其与 Visual Studio 代码(也是电子应用程序)进行比较。它们的文件大小相对非常小,Windows 为 50 MB,rpm 和 deb 软件包为 60 到 70 MB。

我的应用程序很简单,而 Visual Studio Code 具有更多功能。

我想减小文件大小,该怎么做?

我已经看到了这一点,我没有使用电子构建,而是使用电子打包器。在此输入链接描述

这是我在 package.json 中使用的 cmd

packagerLinux: electron-packager --out Linux64 --overwrite --platform linux 
packagerWindows: electron-packager --out winx64 --overwrite --platform windows 
Run Code Online (Sandbox Code Playgroud)

如果您需要,请告诉我

electron visual-studio-code electron-packager

3
推荐指数
1
解决办法
4584
查看次数

构建电子 linux 发行版:找到了 SUID 沙箱助手二进制文件,但未正确配置

我正在为 linux 生成电子发行版。这就是应用程序的构建方式 这是应用程序在 packge.json 中构建的方式

 "builderForLinx": "electron-packager --out linx64 --overwrite --platform linux --appname myApp --asar"  
Run Code Online (Sandbox Code Playgroud)

这个应用程序结构 myApp -> myApp(linux 可执行文件), mian.js, resources -> myApp.asar

这给出了一个 linux 版本的电子包。但是我必须运行以下命令才能运行该应用程序

sudo chmod +x ./myApp
sudo chown root chrome-sandbox
sudo chmod 4755 chrome-sandbox
Run Code Online (Sandbox Code Playgroud)

实际上,我是从 tfs build artifact 获取该应用程序的,当我下载此应用程序时,我想直接运行 ./myApp。

这是我的 tfs 定义,我在 bash 中运行所有这些,而不是我的代理/构建机器是 Windows 机器。

#!/bin/bash 
cd "$(Build.ArtifactStagingDirectory)/myApp" ; pwd
chown <<username>> chrome-sandbox
chmod 4755 chrome-sandbox
Run Code Online (Sandbox Code Playgroud)

注意:$(Build.ArtifactStagingDirectory) 是指向工件目录的 tfs 变量。当我直接在 linux 机器上运行应用程序时,我看到了这个错误

The SUID sandbox helper binary was found, but is not …
Run Code Online (Sandbox Code Playgroud)

linux tfs electron electron-builder electron-packager

3
推荐指数
1
解决办法
3148
查看次数

如何在单元测试中设置html输入元素的文本内容

我正在为角度应用程序运行单元测试,我想通过单元测试设置此输入元素的文本内容。我正在使用茉莉花

<input type="text" id="accountid" class="form-control col-sm-3" [(ngModel)]="record.accountid" name="accountid" required>
Run Code Online (Sandbox Code Playgroud)

我尝试过,但它不起作用

let formData = fixture.debugElement.query(By.css('#accountid'));
formData.nativeElement.value = 22;
fixture.detectChanges();
console.log(formData.nativeElement.textContent);//expected to print 22
expect(formData.nativeElement.textContent).toBe(22);//fails

Run Code Online (Sandbox Code Playgroud)

html unit-testing typescript angular

2
推荐指数
1
解决办法
4509
查看次数

使用自动完成如何过滤多个属性上的对象

我正在开发 Angular 6 应用程序,我想迭代这个对象。我是 rxjs 的新手,我不知道如何根据多个属性过滤对象,尽管我尽力做一些事情。

当我输入名称或类型时,它必须自动完成并过滤对象

这是我尝试过的,但这不起作用

 **template.html**

     <mat-form-field >
        <input matInput [matAutocomplete]="auto"  [formControl]="customerFilterControl">
           <mat-autocomplete #auto="matAutocomplete" [displayWith] = "displayFn">
             <mat-option *ngFor="let option of (filteredOptions | async)" [value] ="option">
               {{option.name}}
             </mat-option>
           </mat-autocomplete>
      </mat-form-field> 

**typescript.ts**

//object 

  objectOptions = [
  { name:'Angular', type:"xyz"  },
  { name:'Angular Material',type:"abc" },
  { name:'React', type:"mnq" },
  { name: 'vue', type:"sds" }
  ];

ngOnInit() {
   this.filteredOptions = this.customerFilterControl.valueChanges.pipe(                    
     startWith(''),
     map(value => this.filterx(value))
   );
 }  

 filterx(value:string):string[] {
     const filterValue = value.toLowerCase();
     return this.objectOptions.map(function(x){if(x.name ||x.type) return x.name; //error detailed …
Run Code Online (Sandbox Code Playgroud)

rxjs angular

2
推荐指数
1
解决办法
2594
查看次数

如何在 Angular 中将变量传递给 css

我正在运行角度应用程序,我计算元素的宽度并将其存储在变量最终位置下,我想移动到左侧(最终位置)px。我希望此样式属性仅在将鼠标悬停在元素上时应用。这个怎么做?

组件.ts


 ngAfterViewChecked(): void {
    this.finalposition = document.getElementById('spandiv').offsetWidth;
  }

Run Code Online (Sandbox Code Playgroud)

组件.html


  <input id="inputCustome" type="text">
  <p id="spandiv">xyzkskssss</p> 
Run Code Online (Sandbox Code Playgroud)

组件.css

#inputCustomer {
  text-align: center;
  position: relative;
  bottom: 7px;
  left: 2px;
}


#spandiv {
  position: absolute;
  right:145px;
  top: 40px;
  background-color: #6B6664;
  padding: 5px;
  color:white;
  font-weight: normal;
  display: block;
  opacity:0;
  overflow: hidden;

}


 #inputCustomer:hover + #spandiv {
  position: absolute;
  left: var(--finalPosition*2)+ "px"; // this value is not getting picked up
  top:40px;
  display: inline;
  opacity:1;

}  

Run Code Online (Sandbox Code Playgroud)

html javascript css typescript angular

2
推荐指数
1
解决办法
1万
查看次数

如何将角度应用程序中的对象数组从一个组件传递到另一个组件

我正在开发角度应用程序。我想使用服务将对象数组从一个组件转移到另一个组件。我正在使用以下链接Pass array of int in Angular Route

通行数据.html

<div>
 <button type="button" [routerLink]="['/receive-data']">Pass Data</button>
</div>
Run Code Online (Sandbox Code Playgroud)

PassData.ts

import ....
@Component({
  selector: 'app-PassData',
  templateUrl: './PassData.component.html',
  styleUrls: ['./PassData.component.css'],
  providers: [DataService]
})

constructor( private dataService: DataService) { }
export class PassData {
  passObjects : any[] = [{'name': 'John', 'city': 'paris'},{'name': 'Bob', 'city': 'london'}, {'name': 'Grim', 'city': 'paris'}];

  passDataToService() {
     this.dataService.storePassedObject(this.passObjects);
  }
    
}
Run Code Online (Sandbox Code Playgroud)

ReceiveData.ts

@Component({
  selector: 'app-ReceiveData',
  templateUrl: './ReceiveData.component.html',
  styleUrls: ['./ReceiveData.component.css'],
  providers: [DataService]
})

export class ReceiveData implements OnInit {
  let selectedProducts = this.DataService.retrievePassedObject();
  console.log(JSON.stringify(selectedProducts)); …
Run Code Online (Sandbox Code Playgroud)

javascript typescript angular

1
推荐指数
1
解决办法
3583
查看次数

JavaScript 中的数组(用于插入和删除)是否有其他替代方法来优化性能

我是 JavaScript 新手,我使用诸如插入和删除元素之类的操作。数组不擅长插入和删除操作。除了 JavaScript 中的 Array 之外,还有其他方法可以执行这些操作吗?就像我们在 Java 中有 ArrayList 一样。

function maintest() {
  deletelem(3);
  insertelem(9845568);
 
}

function deletelem( num ) {
  var value = num;
  var arr = [1, 2, 3, 4, 5, 3]
  arr = arr.filter(function(item) {
      return item !== value
  })
  console.log(arr);
}


function insertelem( num ) {
var value = num;

  var arr = [1, 2, 3, 4, 5, 3]

  arr.splice(2, 0, num);
  console.log(arr);
}
Run Code Online (Sandbox Code Playgroud)
<body onload="maintest()">
  <div id="mainDiv"></div>
</body>
Run Code Online (Sandbox Code Playgroud)

javascript arrays algorithm data-structures

0
推荐指数
1
解决办法
119
查看次数