【问题标题】:Error: Expected one matching request for criteria "Match by function: ", found none错误:预期有一个对标准“按功能匹配:”的匹配请求,但没有找到
【发布时间】:2018-12-30 07:23:32
【问题描述】:

我有一个要测试的userService.spec.ts 文件。代码是这样的。它调用了一个调用ADMIN_API_URL的get函数。我尝试测试给定的文件,但得到了标题中提到的错误。 我的 user.service.spec.ts 文件。

 describe('Service: User service', () => {
 let httpMock: HttpTestingController;
 let userService: UserService;
 let url: string;

  beforeEach(() => {
   TestBed.configureTestingModule({
    imports: [HttpClientTestingModule],
     providers: [
    { provide: AUTH_API_URL, useValue: 'https://auth.example.com/api/' 
      },
    { provide: SSO_API_URL, useValue: 'https://sso.example.com/auth/api/' },
    { provide: WIT_API_PROXY, useValue: 'https://wit.example.com/api/'},
    { provide: ADMIN_API_URL, useValue: 'https://admin.example.com/api/'},
    { provide: REALM, useValue: 'realm' },
    Broadcaster,
    Logger,
    AuthenticationService,
    HttpHandler,
    UserService
  ]
});
httpMock = TestBed.get(HttpTestingController);
url = TestBed.get(ADMIN_API_URL);
userService = TestBed.get(UserService);
 });

 it('Get user by user name returns valid user', (done) => {
const testUser = [{
  'attributes': {
    'fullName': 'name',
    'imageURL': '',
    'username': 'myUser'
  },
  'id': 'userId',
  'type': 'userType'
}];
userService.getUsersByName('name').subscribe((user) => {
  expect(user[1].id).toEqual('userId');
  done();
});
const req = httpMock.expectOne(request => request.method === 'GET'
&& request.url === `${url}search/users?q=name`);
req.flush({data: testUser});
 });
});

我尝试测试所有我想到的东西,但仍然找不到我的代码有什么问题。我犯了什么愚蠢的错误吗?

【问题讨论】:

    标签: unit-testing angular6 karma-jasmine angular7


    【解决方案1】:

    很可能是 URL 不匹配。 expectOne 条件 (request.url === `${url}search/users?q=name`) 可能会失败。您可以记录您的模拟请求 URL 以查看实际 URL 是什么。

    const req = httpMock.expectOne(request => {
        console.log("url: ", request.url);
        return true;
    });
    

    【讨论】:

    • 这不是问题的答案,您应该删除它并在评论中移动它。此外,代码是错误的 - 计算括号,并在“void is not assignable to boolean”中出错。
    • 更正了遗漏的括号。答案是正确的。当 expectOne 预期的 URL 与服务使用的 URL 不同时,会发生错误。代码示例只是为了让提问者可以通过记录来确认传入的 URL,然后可以在条件中修复预期的 URL (request.url === ${url}search/users?q=name)。
    • 这对我在 Angular 10 上不起作用No overload matches this call
    【解决方案2】:

    在我的情况下,测试的服务依赖于其他一些服务,我对此进行了嘲笑。模拟依赖错过了被测试服务调用的模拟函数。这个错误被默默地吞下了。

    添加模拟函数后,它开始正常工作。

    【讨论】:

      【解决方案3】:

      编辑:您描述的问题可能是由“静默”问题引起的。以下是我的经验。

      首先检查您的服务依赖项,例如AuthenticationService 等。

      您创建的请求可能会在管道中进一步与这些依赖项交互,并且可能它甚至到达 Angular 的 HTTP 客户端之前被拒绝!

      这样,HttpTestingController 不会注册请求,您将在测试中得到 found none

      【讨论】:

        猜你喜欢
        • 2021-02-20
        • 2023-03-22
        • 2019-01-08
        • 2018-12-07
        • 1970-01-01
        • 2020-06-21
        • 2018-11-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多