如何解决在Jasmine中调用Angular Component方法后的初始值存储在变量中
// customer-reservation.component.ts
import {Component} from "@angular/core";
@Component({
selector: 'app-customer-reservation',template: ``
})
export class CustomerReservationComponent {
customerCount = 10;
registerCustomer() {
return this.customerCount++;
}
unregisterCustomer() {
return this.customerCount--;
}
}
以下是上述组件的规格文件:
// customer-reservation.component.spec.ts
import {ComponentFixture,Testbed} from "@angular/core/testing";
import { CustomerReservationComponent } from "./customerReservation.component";
describe('Room Reservation',() => {
let fixture: ComponentFixture<CustomerReservationComponent>;
let component: CustomerReservationComponent;
beforeEach(() => {
Testbed.configureTestingModule({
declarations: [
CustomerReservationComponent
]
})
// Set-up
fixture = Testbed.createComponent(CustomerReservationComponent);
component = fixture.componentInstance;
})
afterEach(() => {
// Tear-down
fixture = null;
component = null;
})
it('Increase customer count in case of registration',() => {
let customerCount: number;
customerCount = component.registerCustomer(); // This is still 10
expect(customerCount).toEqual(11); // test fails
})
it('Decrease customer count in case of registration',() => {
let customerCount: number;
customerCount = component.unregisterCustomer(); // This is still 10
expect(customerCount).toEqual(9); // test fails
})
})
我不明白为什么 customerCount
变量在这两种情况下的值为 10。它应该分别为规格存储 11 和 9 值。但是,当我用 customerCount
替换 component.customerCount
时,测试运行成功。有人可以帮助我为什么早期的方法没有更新本地 customerCount
变量与相应测试的递增和递减值。
解决方法
return this.customerCount++;
将始终在递增之前返回 this.customerCount
的值。
要使其与局部变量一起使用,您可以使用前缀递增/递减运算符:
registerCustomer() {
return ++this.customerCount;
}
unregisterCustomer() {
return --this.customerCount;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。