2017-12-04 35 views
16

Đây là một vấn đề thú vị: Tôi đang thử nghiệm một Dịch vụ, sử dụng Ionic BarcodeScanner. Tôi có một repo dựa trên ionic unit-testing repository để thử nghiệm. Tôi đang chế nhạo phương thức BarcodeScanner.scan qua spyOn(..).and.callFake(..)Thử nghiệm các phương thức không đồng bộ (Promise) trong Dịch vụ Góc 2

Vấn đề: Nó hoạt động khi tôi gọi phương pháp quét từ thành phần. Nó ném một thời gian chờ khi tôi làm điều tương tự trong một dịch vụ.

Component mã kiểm tra:

it("should be able to set a spy on the scanner and test the component", done => { 
    const testBC = "123456"; 
    const spy = spyOn(TestBed.get(BarcodeScanner), "scan"); 
    spy.and.callFake(() => { 
     return new Promise((resolve, reject) => { 
      resolve(testBC); 
     }) 
    }); 

     component.testScanner().then(res => { 
      expect(res).toBe(testBC); 
      done(); 
     }, reason => { 
      expect(true).toBe(false); 
      done(); 
     }) 
}); 

Dịch vụ mã kiểm tra:

it("should be able to set a spy on the scanner and test the service", done => { 
    const testBC = "123456"; 
    const spy = spyOn(TestBed.get(BarcodeScanner), "scan"); 
    spy.and.callFake(() => { 
     return new Promise((resolve, reject) => { 
      resolve(testBC); 
     }) 
    }); 

    inject([TestService], (service) => { 
     service.testScanner().then(res => { 
      expect(res).not.toBe(testBC); 
      done() 
     }, reason => { 
      expect(true).toBe(false); 
      done(); 
     }) 
    }) 
}); 

Có bất kỳ vấn đề được biết đến các dịch vụ xét nghiệm tại góc 2 theo cách đó? Bất kỳ trợ giúp nào được đánh giá cao!

Trả lời

6

Vấn đề là không gọi hàm tiêm.

Mã kiểm tra cho dịch vụ bây giờ trông giống như sau:

it("should be able to set a spy on the scanner and test the service", done => { 
    const testBC = "123456"; 
    const spy = spyOn(TestBed.get(BarcodeScanner), "scan"); 
    spy.and.callFake(() => { 
     return new Promise((resolve, reject) => { 
      resolve(testBC); 
     }) 
    }); 

    inject([TestService], (service) => { 
     service.testScanner().then(res => { 
      expect(res).not.toBe(testBC); 
      done() 
     }, reason => { 
      expect(true).toBe(false); 
      done(); 
     }) 
    })(); //<-- do not forget these braces!! 
}); 
Các vấn đề liên quan