Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

MockInstance: ReferenceError: jasmine is not defined #610

Closed
klizter opened this issue May 27, 2021 · 15 comments · Fixed by #620 or #653
Closed

MockInstance: ReferenceError: jasmine is not defined #610

klizter opened this issue May 27, 2021 · 15 comments · Fixed by #620 or #653

Comments

@klizter
Copy link

klizter commented May 27, 2021

I'm having the follow issue with MockInstance in latest version (12.0.2) in combination with jest 27.0.0@next:

 FAIL  src/app/eq/summary/summary.component.spec.ts                                                                                              │Counting objects: 100% (13/13), done.
  ● SummaryComponent › should create                                                                                                                           │Delta compression using up to 12 threads
                                                                                                                                                               │Compressing objects: 100% (7/7), done.
    ReferenceError: jasmine is not defined                                                                                                                     │Writing objects: 100% (7/7), 9.37 KiB | 505.00 KiB/s, done.
                                                                                                                                                               │Total 7 (delta 6), reused 0 (delta 0), pack-reused 0
      at Object.install (../libs/ng-mocks/src/lib/common/ng-mocks-stack.ts:61:5)                                                                               │remote:
      at restore (../libs/ng-mocks/src/lib/mock-instance/mock-instance.ts:43:18)

package.json:

{
  ...
  "dependencies": {
    "@angular/animations": "^12.0.1",
    "@angular/cdk": "^12.0.1",
    "@angular/common": "^12.0.1",
    "@angular/compiler": "^12.0.1",
    "@angular/core": "^12.0.1",
    "@angular/forms": "^12.0.1",
    "@angular/platform-browser": "^12.0.1",
    "@angular/platform-browser-dynamic": "^12.0.1",
    "@angular/router": "^12.0.1",
    "@microsoft/applicationinsights-web": "^2.5.9",
    "@navikt/fnrvalidator": "^1.1.3",
    "@ngxs/router-plugin": "^3.6.1",
    "@ngxs/storage-plugin": "^3.6.1",
    "@ngxs/store": "^3.6.1",
    "@types/hammerjs": "^2.0.36",
    "classlist.js": "^1.1.20150312",
    "date-fns": "^2.16.1",
    "dompurify": "^2.0.15",
    "hammerjs": "^2.0.8",
    "js-cookie": "^2.2.1",
    "ngx-mask": "^11.1.4",
    "ngx-webstorage": "^6.0.0",
    "oidc-client": "^1.10.1",
    "rxjs": "^6.6.7",
    "ts-cacheable": "^1.0.1",
    "tslib": "^2.0.3",
    "uuid": "^8.3.0",
    "wicg-inert": "^3.1.1",
    "zone.js": "^0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^12.0.1",
    "@angular-eslint/builder": "^12.0.0",
    "@angular-eslint/eslint-plugin": "^12.0.0",
    "@angular-eslint/eslint-plugin-template": "^12.0.0",
    "@angular-eslint/schematics": "^12.0.0",
    "@angular-eslint/template-parser": "^12.0.0",
    "@angular/cli": "^12.0.1",
    "@angular/compiler-cli": "^12.0.1",
    "@angular/language-service": "^12.0.1",
    "@babel/core": "^7.11.1",
    "@compodoc/compodoc": "^1.1.11",
    "@ngxs/devtools-plugin": "^3.6.2",
    "@storybook/addon-actions": "^6.1.5",
    "@storybook/addon-essentials": "^6.1.5",
    "@storybook/addon-links": "^6.1.5",
    "@storybook/angular": "^6.1.5",
    "@types/jest": "^26.0.15",
    "@types/node": "^12.12.54",
    "@typescript-eslint/eslint-plugin": "4.16.1",
    "@typescript-eslint/parser": "4.16.1",
    "angular-http-server": "^1.9.0",
    "axe-core": "^4.2.0",
    "babel-loader": "^8.1.0",
    "cross-env": "^6.0.3",
    "cypress": "^7.2.0",
    "cypress-axe": "^0.12.2",
    "eslint": "^7.14.0",
    "eslint-config-prettier": "^6.15.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsdoc": "^30.7.8",
    "eslint-plugin-prefer-arrow": "^1.2.2",
    "eslint-plugin-prettier": "^3.1.4",
    "full-icu": "^1.3.1",
    "jest": "^27.0.0-next.9",
    "jest-preset-angular": "^9.0.0-next.14",
    "jest-teamcity": "^1.9.0",
    "ng-mocks": "^12.0.2",
    "npm-run-all": "^4.1.5",
    "prettier": "^2.2.0",
    "typescript": "^4.2.4"
  }
}
@satanTime
Copy link
Member

satanTime commented May 27, 2021

Hi @klizter,

thanks for the info.

It is interesting, might you share a min example / repo how you run tests without jasmine?
Or a doc / guide on Internet how to do it.

I've seen people using jest-preset-angular which is still relies on jasmine runner, and would be nice to cover projects which use jest without jasmine at all.

Thank you in advance!

@klizter
Copy link
Author

klizter commented May 27, 2021

This is the failing test:

describe("SummaryComponent", () => {
  let component: SummaryComponent;
  let fixture: ComponentFixture<SummaryComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [RouterTestingModule, MockModule(SharedModule)],
      declarations: [
        MockComponent(SummaryComponent),
        MockComponent(AgreementPhoneIconComponent),
        MockComponent(DeliveryOptionSkeletonComponent),
        MockComponent(DeliveryAddressComponent)
      ],
      providers: [
        MockProvider(UpgradeDataStore),
        MockProvider(CustomerService),
        MockProvider(ProductOfferingsService),
        MockProvider("LoadingOverlay", {
          on: () => ({}),
          off: () => ({})
        })
      ]
    }).compileComponents();
  });

  beforeEach(() => {
    MockInstance(ProductOfferingsService, () => ({
      getDeliveryOptions: () => of([])
    }));
    MockInstance(UpgradeDataStore, () => ({
      customer$: of({ id: "1" } as Customer),
      handset$: of({
        minimumPaymentBeforeUpgrade: { includingVAT: 1 } as Price,
        totalPrice: { includingVAT: 2 } as Price,
        monthlyPrice: { includingVAT: 3 } as Price
      } as EquipmentUpgradeProduct),
      authorization$: of({} as AuthorizeApiResponse),
      deliveryAddress$: of({} as DeliveryAddress)
    }));
  });

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

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

Seems like jest@next defaults to using jest-circus as testRunner:

//jest.config.js
require("jest-preset-angular/ngcc-jest-processor");

module.exports = {
  preset: "jest-preset-angular",
  roots: ["src"],
  coverageReporters: ["teamcity", "lcov"],
  coverageProvider: "v8",
  testResultsProcessor: "jest-teamcity",
  transform: {
    '^.+\\.(ts|js|html|css|sass|scss|less|styl)$': 'jest-preset-angular'
  },
  setupFilesAfterEnv: ["<rootDir>/src/jest.setup.ts"],
  moduleNameMapper: {
    "@app/(.*)": "<rootDir>/src/app/$1",
    "@lib/(.*)": "<rootDir>/src/lib/$1",
    env: "<rootDir>/src/environments/environment"
  },
  globals: {
    "ts-jest": {
      tsconfig: "<rootDir>/tsconfig.spec.json",
      stringifyContentPathRegex: '\\.(html|css|sass|scss|less|styl)$',
      astTransformers: ["jest-preset-angular/build/InlineFilesTransformer", "jest-preset-angular/build/StripStylesTransformer"]
    }
  }
};

When I add testRunner: "jest-jasmine2" to the config, the test passes ✅

@satanTime
Copy link
Member

Aha, thanks for the info. I'll add support for the new runner with the next release. It should happen the latest on the upcoming weekend.

@satanTime
Copy link
Member

Hi there,

unfortunately, current implementation of jest-circus doesn't support reporting feature and it breaks functionality of ng-mocks.
I've created a bug report in jest repo: jestjs/jest#11483.

Let's see what they say.

@satanTime satanTime reopened this Jun 4, 2021
satanTime added a commit that referenced this issue Jun 5, 2021
fix(jest): a fix in advance to listen to jest hooks #610
@satanTime
Copy link
Member

v12.1.0 has been released and contains a fix for the issue. Feel free to reopen the issue or to submit a new one if you meet any problems.

@klizter
Copy link
Author

klizter commented Jun 5, 2021

Much appreciated, thank you!! I’ll report back on monday

@satanTime
Copy link
Member

Ah, sorry @klizter, it is a default auto comment because 1 PR was merged.

I've added a fix to ng-mocks. However, jest should add a fix for their library too.
I've created a PR there.
Once they merge and release it, we are fine to go.

@Legiew
Copy link

Legiew commented Jul 14, 2021

Hey, is there a workaround to get ng-mocks working with jest 27 or do we have to wait for their fix?

@satanTime
Copy link
Member

Hi @Legiew,

It is possible:

When I add testRunner: "jest-jasmine2" to the config, the test passes ✅

@satanTime
Copy link
Member

satanTime commented Jul 25, 2021

Hi @klizter,

I hope this finds you well and healthy.

Because of the long delay in merging a fix in jest repo, I decided to provide a framework agnostic approach.
Unfortunately, it is a soft breaking change, which can be fixed quite easily.

If you use MockInstance in it, then you could do something like that: https://github.com/ike18t/ng-mocks/pull/653/files#diff-13fb1b5bcecf12686e433100fed52618b4ae5aa1b9b5c59e85201bef5488a23eR17-R19.

I hope this helps.
Feel free to ping me any time, and happy coding!

satanTime added a commit that referenced this issue Jul 25, 2021
test(e2e): pure jest configuration #610
@satanTime
Copy link
Member

v12.4.0 has been released and contains a fix for the issue. Feel free to reopen the issue or to submit a new one if you meet any problems.

@darioscattolini
Copy link

darioscattolini commented Sep 2, 2021

Hi! I'm having the same error but I'm using Jest v26. I don't create a new thread since perhaps it's just something missing in my jest setup file imports. This is the relevant part of my file's content:

import 'jest-preset-angular/setup-jest';
import 'jest-extended';
import { ngMocks, MockInstance } from 'ng-mocks';

ngMocks.autoSpy('jest');

declare const jasmine: any;
jasmine.getEnv().addReporter({
  specDone: MockInstance.restore,
  specStarted: MockInstance.remember,
  suiteDone: MockInstance.restore,
  suiteStarted: MockInstance.remember
});

@satanTime
Copy link
Member

Hi @darioscattolini,

for v26 it should work well. If you are getting the same error, it should be some other issue. Could you check that your test runner is jasmine? it's in jest's config.

@darioscattolini
Copy link

Hi @satanTime,
My project is a Nx monorepo, and I couldn't find information on the test runner in the config files nor in the imported presets. I guess it uses a custom runner. I've added testRunner: "jasmine2" to the config file for the Angular project and now it works.

@satanTime
Copy link
Member

I see. Thanks for the info.

I'll try to update docs to emphasize how to install ng-mock for jest currectly.

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
4 participants