javascript - 如何以角度为方法 addProduct 编写测试用例
问题描述
我想为一个方法编写测试用例addItem
可能在product.component.spec.ts
文件中。这是我的代码
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
constructor() { }
productName:any
quantity:any
public data:any[]=[
{
"ID": 101,
"Product": "Moto G",
"Quantity": 2,
},
{
"ID": 102,
"Product": "TV",
"Quantity": 4,
},
{
"ID": 105,
"Product": "Watch",
"Quantity": 2,
},
]
ngOnInit(): void {
}
addItem() {
this.data.push({ Product: this.productName, Quantity: this.quantity});
}
}
我开始写product.component.spec.ts
文件
describe('ProductComponent', () => {
let component: ProductComponent;
let fixture: ComponentFixture<ProductComponent>;
fixture = TestBed.createComponent(ProductComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
});
product.component.spec.ts
文件
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from '../app.component';
import { ProductComponent } from './product.component';
describe('ProductComponent', () => {
let component: ProductComponent;
let fixture: ComponentFixture<ProductComponent>;
TestBed.configureTestingModule({
declarations: [
AppComponent,
ProductComponent
]
});
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ProductComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProductComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
解决方案
一个测试用例总是包括 4-5 个步骤:
- 撕毁
- 数据准备
- 执行
- 确认
- (可选)拆除
你已经拥有的是第一步。对于第二步,您需要准备必填字段,data
即quantity
和productName
。
component.productName = 'Awesome Product';
component.quantity = 3;
component.data = [];
第三步只执行你要测试的方法。
component.addItem();
第四步检查结果,现在是扩展数组。
expect(component.data).toEqual([{ Product: 'Awesome Product', Quantity: 3 }]);
推荐阅读
- ios - 如何在 React Native 0.60+ 中添加原生模块?
- youtube-api - YouTube Data API v3 搜索缺失的视频
- amazon-web-services - 如何在公共网络中制作 docker swarm 网络?
- django - 从帖子链接重定向到文件的问题
- jquery - 尝试从使用“追加”切换到具有 [0] 和变量的“追加”
- c# - 添加新的 XEelement 并更新 XML.Descendent
- spring - 为延迟队列实现处理spring kafka的轮询间隔的正确方法是什么?
- javascript - 我是如何用 fetch 填充 vaadin-grid 的?
- r - 在 R 的表中添加几列下面的另一列
- android - 改造 @Patch 方法(更新一个对象,其中包含一个 ArrayList)