unit-testing - 错误: No provider for @Attribute ('sampleString' )

标签 unit-testing angular karma-runner karma-jasmine

我们正在尝试为使用第三方 Java 脚本库的组件编写单元测试。我们组件的构造函数看起来像 -

@Constructor(@Inject(ElementRef) private eleref:ElementRef, @Attribute('sampleString') private sampleString: string)

我们使用该属性将其传递给我的第三方库。它在那里根据该属性执行特定任务。如果我没有通过,就意味着简单地忽略它并做常规的事情。

当我们尝试在测试类中使用/注入(inject)此组件时,它会给我们带来错误。

Error: DI Exception: No Provider for @Attribute('sampleString')!

有人可以建议这方面的提供者是什么吗?如果您的示例可以详细说明此错误的原因以及一般如何解决此类问题,那就太好了。

//component
@component({selector: 'mytable', templateUrl:'URL of template'}
export class mycomp{ 
//data members
constructor (element ref injection, @Attribute('sample string') private sampleString:string){}
//public methods
private ngOninit(){ this.dataview = dataview of third party lib.    }
}

//Test
Describe("my test",()=>{ 
beforeEachProviders(()=>[ mycomp, provider for elementRef]);

It('test', async(inject ([TestComponentBuilder,mycomp], (tcb: TestComponentBuilder) => {
tcb.createAsync(mycomp)
.then ((fixture)=> {
expect(true). toBe(false)
})
 });

最佳答案

该属性需要是

@Attribute('sampleString')

而不是

@Attribute('sampleString')

您需要一个测试组件来包装您实际想要测试的组件,以便能够传递该属性:

@component({
  selector: 'mytable', 
  templateUrl:'URL of template'
}
export class mycomp{ 
  //data members
  constructor (element ref injection, @Attribute('sampleString') private   sampleString:string){}
  //public methods
  private ngOninit(){ this.dataview = dataview of third party lib.    }
}

@component({
  selector: 'test', 
  template:'<mytable sampleString="xxx"></mytable>'
}
export class TestComponent{ 
}

//Test
describe("my test",()=>{ 
  beforeEachProviders(()=>[ mycomp, provider for elementRef]);

it('test', async(inject ([TestComponentBuilder,mycomp], (tcb: TestComponentBuilder) => {
  tcb.createAsync(TestComponent)
 .then ((fixture)=> {
    expect(true). toBe(false)
    // get the mycomp component from fixture ...
  })
});

关于unit-testing - 错误: No provider for @Attribute ('sampleString' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38448301/

相关文章:

javascript - 具有隔离范围的单元测试 AngularJS 指令 - 如何获取输出的绑定(bind)?

r - 如何在单元测试中重用示例?

c# - Azure 持久 HTTPStart 方法中的单元测试 (Rhino) DBUp

java - 如何测试ws-security?

angular - 添加新颜色以及自定义主题颜色 angular2 Material

css - Angular 单元测试 - 忽略样式表

java - 如何避免 Mockito 和 PowerMockito 之间的冲突?

angular - Axios 和 Angular

command-line - 使用模式匹配在 Karma Jasmine 中选择性执行测试

javascript - karma 错误参数 'Controller' 不是函数,未定义