服务未定义的茉莉花测试

时间:2018-07-13 14:39:43

标签: angular jasmine

测试需要订​​阅服务的组件,但是茉莉花测试始终失败

我将服务登录到控制台,并使用expect(contactService).toBeDefined()返回成功

但是一旦我订阅,它就会返回未定义

规格:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ContactComponent } from './contact.component';
import { DivPositionsService } from '../../../services/div-positions.service';
import { ContactService } from '../../../services/contact.service';
import { HttpClientModule } from '@angular/common/http';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { Email } from '../../../models/email.model';
import { HttpClientTestingModule, HttpTestingController } from '../../../../../node_modules/@angular/common/http/testing';
describe('ContactComponent', () => {
  let component: ContactComponent;
  let fixture: ComponentFixture<ContactComponent>;
  let contactService;
  let httpMock: HttpTestingController;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ContactComponent ],
      imports:[
        FormsModule, 
        ReactiveFormsModule, 
        HttpClientModule, HttpClientTestingModule],
      providers:[
        {
          provide: ContactService,
          useValue: jasmine.createSpyObj('contactService', ['sendMail'])
        },
        {
        provide: DivPositionsService,
        useValue: jasmine.createSpyObj('divPositionsService', ['updateObj'])
      }],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ContactComponent);
    component = fixture.componentInstance;
    contactService = TestBed.get(ContactService);
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should create form ngOnInit', () => {
    component.ngOnInit()
    expect(component.contactForm).toBeDefined();
  });
  it('should submit values from form', () => {
    const successMsg = {sucess: true, msg: 'sent'}
    const contact:Email = {
    name:'Test name',
    email: 'Test email',
    message: 'Test message',
    phone: 'Test phone'
    }
    console.log(contactService)
    expect(contactService).toBeDefined()
    contactService.sendMail(contact)
    .subscribe(results => {
      // expect(results).toBeDefined();
      //has to be what is returned by the function
      console.log(results)
      expect(results).toEqual(successMsg);


    });
    console.log(contactService)
  });

});

2 个答案:

答案 0 :(得分:1)

在调用contactService.sendMail(contact),之前,应模拟 sendMail的返回值,类似这样。

contactService.sendMail.and.returnValue(Observable.of(successMsg));

希望有帮助

答案 1 :(得分:1)

首先,您监视contactService,它遵循您提供的代码,没有在任何地方定义。
并且您应该在执行contactSevice函数之前定义compileComponents()

所以你应该做这样的事情。

TestBed.configureTestingModule({
  declarations: [ ContactComponent ],
  imports:[
    FormsModule, 
    ReactiveFormsModule, 
    HttpClientModule, HttpClientTestingModule],
  providers:[
    ...,
    {
    provide: ContactService,
    useValue: class {
      sendMail: () => of({//what ever object you want to return here});
    }
  }],
  schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();

但是上面的方法使您的模拟服务函数被调用,您实际上无法对其进行监视
如果您需要对此进行监视并通过模拟服务执行任何操作

您可以实现这样的模拟类:

class MockContactService {
  sendMail() {
    return of({});
  }
}

let mockContactService;

beforeEach(()=> {
  mockContactService = new MockContactService();
  TestBed.configureTestingModule({
     ...,
     providers:[
       {
         provide: ContactService,
         useValue: mockContactService,
     }],...
  })
  .compileComponents();

  it('what ever', () => {
    spyOn(mockContactService, 'sendMail');
  })
})