Jasmine错误返回:在测试服务时期望返回一个对象

时间:2018-06-18 21:09:32

标签: angular jasmine automated-tests karma-jasmine karma-runner

我目前正在测试添加服务。我试图看看服务是否实际上正在传递我正在嘲笑的模型。它似乎传递它很棒,但我的一个问题是茉莉花期待一个对象,而不是一个数组。运行测试时,我发现了这个错误:

Expected '[{"userId":"1","id":1,"title":"test","body":"test"}]' to equal [ Object({ userId: '1', id: 1, title: 'test', body: 'test' }) ].

现在在我的规范中,我指定我也期待一个对象。我的语法很可能是问题所以输入会很好。这是我的规范:

  it('expects model to be returned,
inject([HttpTestingController, HttpService],
  (httpClient: HttpTestingController, service: HttpService) => {
    // We call the service


    service.add(dummyPost, 'http://localhost:4200/dashboard').subscribe(body => {
    expect(body).toBe(dummyPost)

    });
    // We set the expectations for the HttpClient mock
     const req = httpClient.expectOne({ url: 'http://localhost:4200/dashboard', method: 'POST'});
       expect(req.request.body).toEqual(jasmine.objectContaining(dummyPost)); req.flush(dummyPost);


  });

模拟模型:

 const dummyPost: Test[] = [
  {userId: '1', id: 1, title: 'test', body: 'test'},

];

此模型结构来自模型typescript类。任何帮助都会很棒。我认为问题在于茉莉花期望返回一个对象,而不是一个数组。如果有帮助,这是我正在测试的服务:

 add(model, url: string): Observable<any[]> {
    let headers = new HttpHeaders({
        'Content-Type':
        'application/json; charset=utf-8'
    });
    let options = { headers: headers };
    let body = JSON.stringify(model);
    return this.http.post(url, body, options)
        .map(this.extractData)
        .catch(this.handleErrorObservable);
 }

谢谢!

1 个答案:

答案 0 :(得分:0)

我通过在对象上使用Json.stringify对其进行了修复。

__imp_apr_hash_set