简体   繁体   中英

Angular Apollo V3 - Jest error: Cannot find module 'apollo-angular'

I recently updated angular apollo from 2.6.0 to the v3.0.0 and this update broke my tests.

I am using jest for my unit tests, while the app compiles and runs fine, my tests are unable to import any dependency from 'apollo-angular', and I get errors like this:

  Test suite failed to run

    Cannot find module 'apollo-angular' from 'src/graphql/generated/graphql.ts'

    Require stack:
      src/graphql/generated/graphql.ts
      src/app/pages/test/test.component.ts
      src/app/pages/test/test.component.spec.ts

      1 | /* eslint-disable */
    > 2 | import { gql } from 'apollo-angular';
        | ^
      3 | import { Injectable } from '@angular/core';
      4 | import * as Apollo from 'apollo-angular';
      5 | export type Maybe<T> = T | null;

      at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:324:11)
      at Object.<anonymous> (src/graphql/generated/graphql.ts:2:1)

There is an order on the module resolution and because 'apollo-angular' v3 is using .mjs the resolved file will be package.json (in node_modules/apollo-angular/package.json ), the package.json containing the 'module' property

{
  "module": "build/fesm2020/ngApollo.mjs",
}

In short, when importing import * as Apollo from 'apollo-angular' I expect jest to resolve node_modules/apollo-angular/package.json which one will point to build/fesm2020/ngApollo.mjs which is the expected file to import.

Again, TS is compiling the project properly and is able to import this es module but jest it not. What did I miss?

Seems that I was using an old version of jest-preset-angular

"jest-preset-angular": "^9.0.7",

I updated to

"jest-preset-angular": "^11.1.1",

I then had a minor breaking change that I fixed removing the import 'jest-preset-angular/setup-jest'; line from my setup-jest.ts file and the bug is gone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM