繁体   English   中英

单元测试用例,用于不返回但调用其他功能的函数

[英]unit test case for a function which doesn't returns but calls other function

我正在使用angularjs(1.x)作为框架进行项目。 在这个项目中,我有一个Web界面,我提出了一些后端请求。 我觉得有必要为这个工具编写测试。 所以,我开始为此编写单元测试用例。 但是现在,我无法为某些功能编写测试用例。 我的问题是:

我正在尝试编写正在发出后端请求的函数的测试用例,并且无论是success还是error ,我都在调用其他函数。 所以,基本上,这个函数没有返回任何东西。 那么,我如何测试这个功能呢?

代码段是:

public makePutRequest(): void {
    this.backendService.putBackendRequest(url, backendData, config)
    .then((success) => {
        successFunction(success); // function call on success
    }, (error) => {
        errorFunction(error);   // function call on error
    })
}

backendService中的函数是:

public putBackendRequest(url, backendData, config){
    let defered = this.$q.defer();
    this.$httpService.put(url, backendData, config)
        .success((data, status, headers, config): void => {
            if (status === 200) {
                // do some further manipulation with data.
            }
            return defered.resolve(data);
        })
        .error((data, status, headers, config): void => {
            if (status === 500) {
                // do some other manipulation.
            }
            return defered.reject(data);
        });
    return defered.promise;
}

我正在编写单元测试测试用例,使用karma作为测试运行器,jasmine作为测试框架,使用angularjs(1.x)作为框架。

现在,我无法弄清楚如何为函数makePutRequest编写测试用例,因为它正在获得promise ,并且在resolve promise时它正在调用一个函数而在reject它正在调用其他函数。

我是新手在angularjs中编写单元测试。 任何有用的建议都会非常有用!

谢谢

您想为backendService构建测试双精度。 测试双重将根据您的要求拒绝或解决。 您没有提到您正在使用的单元测试框架,但是您可以手动构建测试双精度,或者使用单元测试中的模拟框架来制作测试双精度,以您想要的方式响应。 一些测试库,如Jasmine,可以创建内置的测试双精度。

以下是针对相同类型的服务(调用后端的服务)手动构建的测试双精度的示例。 您需要某种机制将测试double注入调用服务的测试代码中。 在下面的示例中,我使用构造函数依赖注入。

正在测试的课程是“App”。 App调用的依赖项/服务称为“Api”。 在下面的示例中,我测试的是,在App成功接收服务返回的已解析承诺中的数据后,它会在App上正确更新状态。

  it('loads drugs when attached to dom', function(done) {

    let response = new Response(JSON.stringify(
      [{drugId : "1", name: "drug1", classifications : []}]
    ));

    let fetchPromise = new Promise(function(resolve) {
      resolve(response.json());
    });

    let mockApi = { getDrugs : function() {
      return fetchPromise;
    }};

    let app = new App(mockApi);

    app.attached();

    fetchPromise.then( function() {
      expect(app.availableDrugs.length).toBe(1);
      expect(app.availableDrugs[0].drugId).toBe("1");
      expect(app.availableDrugs[0].name).toBe("drug1");
      done();
    });
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM