使用Jasmine进行服务的单元测试不会返回数据

时间:2020-06-05 12:13:54

标签: jasmine karma-runner angular9

伙计们!我是测试人员的新手,并且一直坚持这个问题。我正在尝试为我的服务编写单元测试,该测试从服务器获取数据。经典案例:

public static String returnEmployeeName(String ID) throws ClassNotFoundException, SQLException {
    HashMap<String, String> infoHR = connectionInfoHR();

    String query = "SELECT first_name FROM employees WHERE employee_id = '" + ID + "'";

    Class.forName("com.mysql.cj.jdbc.Driver");

    Statement st;
    ResultSet rs;
    Connection con;

    try (con = DriverManager.getConnection(infoHR.get("url"), infoHR.get("uname"), infoHR.get("pass"))) {
        //Error on line above relating to not initialising the object within the statement

        st = con.createStatement();
        rs = st.executeQuery(query);

        rs.next();
        return rs.getString("first_name");

    } finally {

        st.close();
        con.close();
    }
}

我在服务文件中的方法如下:

import {TestBed} from '@angular/core/testing';
import {ShiftsService} from "./shifts.service";
import {Shift} from "../shift/shift";

describe('ShiftService - testing HTTP request method getShifts()', () => {
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [ShiftsService]
    });
  });

  it('can test HttpClient.get', () => {
    let shifts = new Array<Shift>();
    let shiftsService;
    let calendarMonth = new Date().getMonth()+2;
    let calendarYear  = new Date().getFullYear();
    shiftsService = TestBed.inject(ShiftsService);
    httpTestingController = TestBed.inject(HttpTestingController);
    shiftsService.getShifts(calendarYear, calendarMonth).subscribe(response => {expect(response).toBe(response.length);
    console.log(response);
    });

    let apiRequest:string = '/api/shifts?year='.concat(calendarYear.toString()).concat('&month=').concat(calendarMonth.toString());
    const req = httpTestingController.expectOne(apiRequest);
    console.log(apiRequest);
    expect(req.request.method).toBe('GET');

    req.flush(shifts);
  });

  afterEach(() => httpTestingController.verify());
});

我得到了错误:错误:预期[]为0。当我打印出 response 变量时,我发现它是空的!但我敢肯定,这种方法可以正常工作!在我的应用程序中效果很好!您能帮我解决这个问题吗?如何更正我的测试方法以测试服务?

1 个答案:

答案 0 :(得分:1)

最后,您正在做req.flush(shifts)shifts = new Array<Shift>();,本质上是[]。刷新是您希望HTTP get请求响应的内容,在这种情况下,它是一个空数组。

在订阅中,您声明response[])等于response.length,即0

尝试一下:

it('can test HttpClient.get', (done) => { // add done callback to be able to call it in the subscribe
    let shifts = new Array<Shift>();
    let shiftsService;
    let calendarMonth = new Date().getMonth()+2;
    let calendarYear  = new Date().getFullYear();
    shiftsService = TestBed.inject(ShiftsService);
    httpTestingController = TestBed.inject(HttpTestingController);
    shiftsService.getShifts(calendarYear, calendarMonth).subscribe(response => {
       // we have to use toEqual because toBe does a deep assertion
       // but the array to compare to is in a different location in memory so 
       // toBe would fail
       expect(response).toEqual([]);
       console.log(response);
       // call done to tell the unit test you are done with this test
       done();
    });

    let apiRequest:string = '/api/shifts?year='.concat(calendarYear.toString()).concat('&month=').concat(calendarMonth.toString());
    const req = httpTestingController.expectOne(apiRequest);
    console.log(apiRequest);
    expect(req.request.method).toBe('GET');

    shifts.push(/* push a shift here */) // change the shifts array to what you want the server to respond with 
    req.flush(shifts);
  });
相关问题