简体   繁体   中英

Angular test does not include import from node_modules

I cannot resolve an external library via node_modules in a test in angular 2. Am I missing something?

I have a service that imports a library from node_modules:

import {Injectable} from '@angular/core';
import Lib from 'lib';
@Injectable()
export class Service { 
  stuff() {
    return Lib.doStuff();
  }
}

When I run the application, Lib is defined and I can use the library.

When I run a test on that class, the Lib is undefined.

describe('tests', () => {
  let service: Service;
  beforeEach(() => service = new Service());
  it('test', () => {
    service.stuff();
  });
});

The test itself works. If I test for a hardcoded return value it works, so the overall setups seems to be fine.

I use a project skeleton created with angular-cli. Some versions:

@angular/cli: 1.0.0
node: 6.10.2
os: linux x64
@angular/common: 4.0.2
@angular/compiler: 4.0.2
@angular/core: 4.0.2
@angular/forms: 4.0.2
@angular/http: 4.0.2
@angular/platform-browser: 4.0.2
@angular/platform-browser-dynamic: 4.0.2
@angular/router: 4.0.2
@angular/cli: 1.0.0
@angular/compiler-cli: 4.0.2

Im quite new to angular, so i have no clue what happens behind the curtains. I would expect that all imports just get resolved.

Isn't that the case?

you can only using import Lib from 'lib' if your lib export default the Lib symbol, if not you need using one of formular such as:

import * as Lib from 'lib'

or

import {Lib} from 'lib'

learn more about import in Mozilla Developer Network

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