角度单元测试 - 反应形式值未更新

2023-12-13

我是角度单元测试的新手。 测试场景:html中的表单视图值等于组件表单值。 电子邮件值由共享值检索并在组件注册表单中使用。我可以使用反应式表单从组件中检索电子邮件值,但是当尝试通过本机元素访问时,它给出了空。 下面是component.ts

ngOnit(public serviceEmail) {
    this.assignEmailAvailable();
    this.createRegistration();

    }
assignEmailAvailable() {
 if(service.email){
    this.email = serviceEmail.email;
  }
 }   
createRegistration() {
   this.registerForm = new FormGroup({
       email:new FormControl({value:this.email})
    })
}

在 component.spec.ts 中,我将调用此函数并检查两个值是否相同。 组件规格

 beforeEach(() => {
    fixture = TestBed.createComponent(RegisterComponent);
    component = fixture.componentInstance;
    service = TestBed.get(serviceEmail);
  });
it('Registration Form Creation', fakeAsync(() => {
    service.email = "[email protected]";

    fixture.detectChanges();

    component.assignEmailAvailable();
    component.createRegisterForm();

    fixture.detectChanges();
    fixture.whenStable().then(() => {
    const email = fixture.debugElement.query(By.css('input[id="email"]')).nativeElement;
//The value is empty even after creating the form using the component function
    expect(email.value).toBe(component.emailValue);
    });
//THis returns me the value set
    expect(component.registerForm.get('email').value).toBe(component.emailValue);
  }));

我花了大约 2 个小时试图解决这个问题。根据我的经验,您的 beforeEach() 函数中存在一些需要解决的问题。首先,您需要将 ReactiveFormsModule 导入到 TestBed 中,以便更改检测正确执行所有操作。其次,您需要在 beforeEach() 调用中手动运行 ngOnInit() 和 Fixture.DetectChanges() 来设置表单。请参阅下面的 beforeEach() 函数。我还包含了其他遇到此问题的人可能会发现相关的代码的其余部分。

组件模板:


<form [formGroup]='emailForm' (ngSubmit)='handleSubmit()'>
  <div class='form-group'>
    <label for='email'>Email address</label>
    <input type='email' class='form-control' id='email' placeholder='Enter email'
      formControlName='email'>

组件 TS:

  constructor(
    private apiService: ApiService,
    private fb: FormBuilder,
    private router: Router
  ) { }

  ngOnInit() {
    this.initializeForm();
  }

  initializeForm(): void {
    this.formSubmitted = false;
    this.serverProcessing = false;
    this.emailForm = this.fb.group({
      email: ['', Validators.compose([Validators.required, Validators.email])]
    });
  }

  get email() {return this.emailForm.get('email');}

Spec TS 中的 beforeEach() 调用:

beforeEach(
async(() => {

  apiServiceSpy = jasmine.createSpyObj('ApiService', ['sendResetPasswordEmail']);
  routerSpy = jasmine.createSpyObj('Router', ['navigateByUrl']);

  TestBed.configureTestingModule({
    declarations: [ SendPasswordResetEmailComponent ],

    // Need to import this if we're messing with Reactive Form inputs!!
    imports: [ReactiveFormsModule],

    providers: [
      {provide: ApiService, useValue: apiServiceSpy},
      {provide: Router, useValue: routerSpy},
      {provide: FormBuilder},
    ]
  })
  .compileComponents();
})
);

beforeEach(() => {
    fixture = TestBed.createComponent(SendPasswordResetEmailComponent);
    component = fixture.componentInstance;

    // ngOnInit() doesn't get called automatically, so we have to do it ourselves
    component.ngOnInit();

    // Telling the fixture to detect changes is really important to correctly bind data
    // Do this after calling ngOnInit() so changes propagate to the template 
    fixture.detectChanges();
});

测试规格样本:

it('should have an error for no username', () => {
    const componentElement: HTMLElement = fixture.nativeElement;
    const emailInput: HTMLInputElement = componentElement.querySelector('input');
    emailInput.value = '@gmail.com';
    emailInput.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    expect(component.email.errors.email).toBeTruthy('@gmail.com valid');
});

it('should have no error if the email is valid', () => {
    const componentElement: HTMLElement = fixture.nativeElement;
    const emailInput: HTMLInputElement = componentElement.querySelector('input');
    emailInput.value = '[email protected]';
    emailInput.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    expect(component.email.errors).toBeFalsy('[email protected] invalid');
    });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

角度单元测试 - 反应形式值未更新 的相关文章

随机推荐

  • 全屏应用程序 WM6 C#

    谁能指导我如何使用 C 创建适用于 Windows Mobile 6 的全屏应用程序 我正在尝试实现与 Tom Tom 等应用程序类似的显示 其中隐藏了所有操作系统元素 例如开始 任务栏 并且我的应用程序完全填满了屏幕 我正在使用 VS 2
  • 连接到 BLE 设备

    所以我制作了这个应用程序 我可以在其中找到所有具有名称的 BLE 设备 但是我怎样才能使特定字段之一可单击并自动连接到设备 以便我可以开始从中写入 读取呢 Adapter public class ListAdapter BTLE Devi
  • 如何在Spritekit中创建风效果

    我在玩 愤怒的小鸟 到了这个阶段 风 吹 你 有点推你 有点有趣 但我真的无法弄清楚可以完成此操作的逻辑或代码 我知道你可能会使用发射器来创建像 看 一样的风 但我真的很想了解如何完成精灵的 推动 谢谢 你是对的 发射器只能用来产生风在吹的
  • 阅读:hover 伪类与 javascript

    我做了一个函数来覆盖 hover页面上的某些元素 它在正常和正常之间消失 hover 影响 因为我必须创建一个 hover我的 CSS 文件中的类 我觉得这有点不干净 我怎样才能读到 hover伪类内容 Using getComputedS
  • 使用 Cypher 2.0 将 Lucene 查询传递到 Neo4j REST API

    如果我有一个 Lucene 查询 例如 title foo bar AND body baz OR title bat有没有直接的方法可以将其传递到 Cypher 查询中 它看起来像这样用来工作START和旧的node auto index
  • 我可以像数组一样使用 stdClass 吗?

    是否可以使 stdClass 对象像通用索引数组一样工作 IE 数组 数组 0 gt 120 1 gt 382 2 gt 552 3 gt 595 4 gt 616 会被构造成像 a array array 120 array 382 et
  • 手动计算SVM的决策函数

    我正在尝试使用Python库SKLearn手动计算SVC分类器的decision function 而不是使用内置方法 我已经尝试了几种方法 但是 当我don t扩展我的数据 z是一个测试数据 已缩放 我认为其他变量本身就说明了问题 另外
  • 在新 Intent 中显示 TabHost 布局时出现问题

    我在 TabActivity 类型的新 Intent 中使用 TabHost 时遇到问题 希望您能为我指出正确的方向 有趣的是 当我尝试在原始意图中查看它时 它工作正常 setContentView R layout main 我收到 强制
  • 为什么我无法在 HTML 标签内插入注释?

    有什么原因导致我无法在 HTML 标记内插入注释吗 示例 HTML 格式 不可能 img src alt Sample Picture class img circle center block gt 而在 JavaScript 中 这可以
  • ServiceStack:存在时从目录提供静态文件吗?

    我正在将我的独立的自制 Web 服务器转换为使用 ServiceStack 来提供所有页面和资源 从这个问题我看出 使用 servicestack 提供静态文件 使用服务堆栈提供单个静态文件很容易 在我自己开发的实现中 在检查 URL 是否
  • WebRTC - 从 Chrome 但不是 Firefox 获取“格式错误的约束对象”

    我想知道我做错了什么 我从中收到 格式错误的约束对象 错误 pc createAnswer function answer fail offerToReceiveAudio true offerToReceiveVideo true 有任何
  • 处理十六进制之间的转换

    我想构建一个函数来轻松地将包含十六进制代码的字符串 例如 0ae34e 转换为包含等效 ascii 值的字符串 反之亦然 我是否必须将十六进制字符串切成两个值对 然后再次将它们组合在一起 或者是否有一种方便的方法可以做到这一点 thanks
  • C#:可空结构上的默认文字和类型推断

    从 C 7 1 开始 可以通过使用获取默认值default不指定类型 我今天尝试了一下 发现可为空结构和可为空值类型的结果有些违反直觉 TestFixture public class Test private class Person p
  • 将 10 位数字转换为十六进制字符串

    如何在 C 中将 10 位数字转换为十六进制字符串 Note 如果数字少于10位 我想添加填充 例子 数字是 1 我希望我的字符串是 0000000001 Use a 标准格式字符串 string paddedHex myNumber To
  • Eigen::Ref<> 作为成员变量

    我需要一个类有一个 Eigen Ref 变量作为静态成员 该变量将通过init静态方法 像这样的东西 class CostFunction public static Eigen Ref
  • 在 Google Analytics 中组合相似的 URL(有一些变化)

    我有很多类似的网址 我想将它们合并到 Google Analytics 分析 中 我已经成功地合并了其中的很多 然而我现在遇到了一些问题 我的 URL 看起来像这样 文章 4567 编辑文章 87478548 编辑 文章 82984786
  • 当您订阅ngrx中的商店时,如何访问以前的状态和当前状态并进行比较?

    在我的组件中 我订阅了 ngrx 存储 该存储在给定状态发生变化时触发 我想设置一个条件 如果当前状态和以前的状态不同 那么我会执行一些操作 如何获取之前的状态 this store select testPortfolio subscri
  • Android 视频方向在 mediarecorder.Start() 上发生变化

    这个问题和帖子类似here here here here and here 但我被困住了 花了几个小时试图弄清楚 我有一个摄像机预览 现在总是以正确的方向显示 但是当我点击录制 mediaRecorder start 时 视频方向会发生变化
  • 在 C++ 中防止名称空间中毒的优雅方法

    我们假设 Bob已将他的库包装到名称空间中 bob and Alice将使整个命名空间在她自己的函数中可见 使用命名空间鲍勃 代替 使用鲍勃 XYZ 对于每一个项目 This file is written by Alice include
  • 角度单元测试 - 反应形式值未更新

    我是角度单元测试的新手 测试场景 html中的表单视图值等于组件表单值 电子邮件值由共享值检索并在组件注册表单中使用 我可以使用反应式表单从组件中检索电子邮件值 但是当尝试通过本机元素访问时 它给出了空 下面是component ts ng