2017-10-06 82 views
0

我想为私有变量编写单元测试。但茉莉花不允许我使用它。有人能解释我该怎么做吗?使用私有变量进行角单元测试

export class TestComponent implements OnInit { 
    private resolve; 

    public testPrivate() { 
    this.resolve(false); 
    } 
} 

it(
     'should test private variable',() => { 
     component.testPrivate(); 
     expect(component.resolve).toEqual(false); 
}); 

回答

1
expect(component['resolve']).toEqual(false); 

expect((<any>component).resolve).toEqual(false); 
enter code here 

然而,在技术上你不应该测试私有变量仅仅是因为它是一类private成员,它的意思是只在类本身访问,如果你真的想测试它,你必须公开它或为它创建公开的gettersetter

顺便说一句,除非你没有在这里写完整个测试,否则你的测试对我来说没有什么意义。

因为你打电话给this.resolve(false),这意味着它是一个函数,那么为什么你测试它等于false

编辑:

你的意思是这样的:?

public testPrivate() { 
    this.resolve = false; 
} 
+1

或'(component as any).resolve' – yurzui

+0

TypeError:this.resolve不是函数。尝试第一种方法时出现此错误。 – Ish

+1

当然不是,:)你是什么意思? – Milad