如何通过 jest 提供 @inject 构造函数参数

How to provide an @inject constructor param via jest

我有服务

@Injectable({
  providedIn: 'root',
})
export class MyService {
  constructor(private readonly _http: HttpClient, @Inject('env') private env) {}

  getData(): Observable<string> {
    return this._http.get<string>(`${this.env.webApiBaseUrl}data`);
  }
}

和测试

describe('MyService', () => {
  let service: MyService;
  let env = { webApiBaseUrl: 'https://our-nifty-api/' } as any;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule],
      providers: [MyService, { provide: env, useValue: env }]
    });
    service = TestBed.inject(MyService);
  });

通常我会模拟 httpClient 和响应等。但在这种情况下,API 也将被测试。所以我必须同时提供可用的 httpClient 和环境参数。

但是后面怎么提供呢?

依赖项应该是一个字符串

describe('MyService', () => {
  let service: MyService;
  let env = { webApiBaseUrl: 'https://our-nifty-api/' } as any;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule],
      providers: [
        MyService,
        {
          // HERE IS THE RIGHT DECLARATION
          provide: 'env',
          useValue: env
        }
      ]
    });
    service = TestBed.inject(MyService);
  });