【问题标题】:Can't resolve all parameters + error + for service unit testing无法解析所有参数+错误+服务单元测试
【发布时间】:2021-04-17 02:23:21
【问题描述】:

我收到以下错误:..

Can't resolve all parameters for Service1: (?, ?).

Service1.ts
export class Service1 {
constructor(protected url: string, protected http: HttpClient) { }
}

Service1.spec.ts
describe('Service1', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [Service1],
    });
  });

    it('should be created', () => {
      const service1: Service1 = TestBed.get(Service1);
      expect(service1).toBeTruthy();
  });
});

在这里只模拟了 httpclient 模块,如果它模拟 url:stirng 部分它会起作用,我想是的。那么我怎样才能模拟和 makke 测试通过?。

【问题讨论】:

  • 您正在尝试将url 字符串注入服务。 Angular 无法知道应该在此处注入哪个 url,因此这在测试和应用程序本身中都应该失败。

标签: angular unit-testing jestjs


【解决方案1】:

问题是 Angular 不知道要为 protected url: string 注入什么。

因此,您需要为其提供令牌。

// Service1.ts
export const APP_URL = new InjectionToken('APP_URL');

export class Service1 {
constructor(
  @Inject(APP_URL) protected url: string,
  protected http: HttpClient,
) { }
}
// Service1.spec.ts
describe('Service1', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        Service1,
        {
          provide: APP_URL,
          useValue: 'mock',
        },
      ],
    });
  });

    it('should be created', () => {
      const service1: Service1 = TestBed.get(Service1);
      expect(service1).toBeTruthy();
  });
});

【讨论】:

    猜你喜欢
    • 2017-11-13
    • 2016-11-18
    • 1970-01-01
    • 2017-11-20
    • 2019-03-16
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多