如何在类中模拟私有方法?

时间:2019-08-28 09:06:22

标签: unit-testing jestjs nestjs

在Nestjs中,我想模拟服务私有方法。开玩笑地说,使用spyOn方法无法访问私有方法。在这种情况下该怎么办?

operation.service.ts

private async _getOperationDocument(id): Promise<OperationDocument> {
  return await this.operationDocumentService.findById(id);
}

operation.service.spec.ts

jest
  .spyOn(service, '_getOperationDocument')
  .mockImplementation(async id => {
    return OperationDocumentMock as OperationDocument;
  });

2 个答案:

答案 0 :(得分:1)

我有2件事情。

  1. 您有一个单行方法,可以简单地调用另一个方法。我想说您根本不需要这种方法,您将添加无用的层,使代码复杂化,根本没有任何好处。

  2. 即使您最终保留了它,嘲笑它也没有意义。您最好模拟它正在调用的方法。

答案 1 :(得分:0)

由于@ Andrei-Dragotoniu,我最终模拟了该服务。

function make_list_regios(){
global $post;
$output = '<ul>';
$post_idees = new WP_Query(array('post_type' => 'bedrijf'));
$values = wp_list_pluck( $post_idees->posts, 'ID');
foreach( $values as $value ) {
            $meta_values[] = get_post_meta( $value, 'elements', true );
            $meta_values2 = array_filter($meta_values);
            $meta_values3 = call_user_func_array('array_merge', $meta_values2);
}
foreach($meta_values3 as $meta_value3){
            $output .='<li>'.$meta_value3.'</li>';
            }
            $output.='</ul>';
            return ($output);
}
add_shortcode('regios', 'make_list_regios');

已在另一个经过测试的方法中调用了私有方法。

相关问题