【问题标题】:how to fix Error: ASSERTION ERROR: Should be run in update mode [Expected=> false == true <=Actual]如何修复错误:断言错误:应该在更新模式下运行 [预期 => 假 == 真 <= 实际]
【发布时间】:2021-04-19 01:34:57
【问题描述】:

我正在用 ChangeDetectorRef 编写一个带有角度的代码

函数本身运行良好。

getVersionInfos() {
concat(
  of(
    this.getApiSubs = this.aboutInfoService.getApiVersion().subscribe((data) => {
      if (data) {
        this.apiData = data;
        this.applicationCopyright = data.find(dt => dt.Name === "Web API Details").Value;          }
    })
  ),
  of(
    this.getEngineSubs = this.aboutInfoService.getEngineVersion().subscribe((data) => {
      if (data) {
        this.engineData = data;
        this.engineDetails = data.find(dt => dt.itemcode === "VER").versiontext;
        this.cd.detectChanges();
      }
    })
  )
);

}

当我为它编写单元测试代码时,它一直在失败

        this.cd.detectChanges();

这给了我这个错误

错误:断言错误:应该在更新模式下运行 [预期=> false == true

这是规范代码块

beforeEach(async(() => {
TestBed.configureTestingModule({
  declarations: [
    AboutComponent
  ],
  imports: [
    MatBottomSheetModule,
    HttpClientTestingModule
  ],
  providers: [
    {
      provide: AboutInfoService,
      useValue: jasmine.createSpyObj("AboutInfoService", [
        "getApiVersion",
        "getEngineVersion"
      ]),
    },
    {
      provide: ChangeDetectorRef,
      useValue: jasmine.createSpyObj("ChangeDetectorRef", ["detectChanges"])
    }
  ]
})
.compileComponents();

aboutInfoService = TestBed.get(AboutInfoService);
aboutInfoService.getApiVersion.and.returnValue(of(mockApiResponse));
aboutInfoService.getEngineVersion.and.returnValue(of(mockEngineResponse));



}));

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

  it("should create", () => {
    expect(component).toBeTruthy();
  });

如果我删除代码

        this.cd.detectChanges();

从函数中它将通过单元测试

【问题讨论】:

  • 你在组件的构造函数中调用getVersionInfos函数吗?
  • 谢谢,我把函数的位置改了,放到了ngOnInit @shalom

标签: angular typescript jasmine karma-jasmine


【解决方案1】:

一切顺利,

我已将函数 getVersionInfos 放在 ngOnInit 中,而不是放在构造函数中

【讨论】:

    【解决方案2】:

    我在 Angular 11 中也有这个错误。问题是我正在执行:

    this.cdr.detectChanges();
    在构造函数内部,这是错误的。我把它移到 ngOnInit()

    【讨论】:

      【解决方案3】:

      避免将this._changeDetectorRef.detectChanges() 方法调用保留在构造函数或将从构造函数调用的方法中。 Angular 在这两种情况下都会抛出这个错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-20
        • 1970-01-01
        • 2022-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-08
        相关资源
        最近更新 更多