Angular 模拟规范

Angular mock Spec

我就是这样使用 ng-mocks -

import { MockDirective, MockComponent, ngMocks } from 'ng-mocks';

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ 
                      MockComponent(ComponentName),

      ],

      schemas:      [ NO_ERRORS_SCHEMA ]

    })
    .compileComponents();
  }));

我看到以下错误 -

Failed: ng-mocks is not in JIT mode and cannot resolve declarations

此问题最近已得到修复。在您的情况下,这意味着 ComponentName 导入错误,或者类型错误。

MockComponent 接受 类。因此,它应该像这样使用:

import { MockDirective, MockComponent, ngMocks } from 'ng-mocks';

beforeEach(() => {
  TestBed.configureTestingModule({
    declarations: [ 
      MockComponent(ComponentClass), // <- its class instead of its name.
    ],
  }).compileComponents();
}));

将我的项目从 angular @12.2.16 升级到 @13.2.4 后出现此错误。但是我得到了完全相同的错误:

MyComponent declaration has been passed into ng-mocks without Angular decorators. Therefore, it cannot be properly handled. Highly likely, jest.mock() has been used on its file, or ng-mocks is not in JIT mode

我的项目版本:

  • ng-mocks: 12.5.1
  • @angular/core: 13.2.4

在尝试了很多可能的解决方案后,一个可以解决我的问题,只需重新安装 ng-mocks 最新版本,一切都已修复,所有测试都成功通过。

更新 ng-mocks 到最新版本:

$ npm uninstall ng-mocks
$ npm install ng-mocks@latest --save-dev

祝你好运,希望这对其他人有所帮助。