angular - 无法读取未定义的“管道”
问题描述
我正在尝试对角度组件进行单元测试。我是单元测试的新手,我目前面临以下问题
我的组件有如下选择语句:
this.store.select(getInfo)
.pipe(takeWhile(() => this.isLive)
)
.subscribe((data) => {
this.text = data;
});
我的单元测试用例是这样写的:
fdescribe(‘TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
const testStore = jasmine.createSpyObj('Store', ['select']);
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TestComponent
],
imports: [MaterialModule, FiltersModule],
providers: [
{provide: Store, useValue: testStore }],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create Test component', async() => {
let initialState = {
data: {
“name: “xyz”,
“age” : 20
} ,
info: [1]
};
testStore.select.and.returnValues(
of(initialState.info)
);
fixture.detectChanges();
await fixture.whenStable();
expect(component).toBeTruthy();
});
it('should have at least 1 info’, async() => {
let initialState = {
data: {
“name: “xyz”,
“age” : 20
} ,
info: [1]
};
testStore.select.and.returnValues(
of(initialState.info)
);
fixture.detectChanges();
await fixture.whenStable();
console.log("text is ",component.text);
});
});
这是一个非常幼稚的测试。在继续编写更复杂的测试之前,我只是想了解基本概念。所以,我面临的问题是。它提示我一个错误说: TypeError: Cannot read property 'pipe' of undefined 并且这只发生在 ''should create Test component' testcase 。其他测试用例按预期登录消息。
我无法理解我哪里出错了。
解决方案
当您提供服务时,每个测试都会获得所提供对象的单独副本。您正在将 testStore.select 的值设置为测试本身内部的原始对象。你有两个选择。第一个是testStore.select
在你在 beforeEach 中声明 Jasmine 间谍之后立即设置。第二个选项是在测试中获取对 testStore 的引用并分配给它。
const service = TestBed.get(Store) as Store;
service.select = jasmine.createSpy('select').and.returnValue(of(info));
您选择哪个选项取决于您。由于我没有看到对组件方法的调用,因此我假设您显示的组件代码是从 onInit 调用的。在这种情况下,第一个选项更易于使用。
如果您想更改info
每个测试的外观,您可以使用选项二,或者component.onInit()
在设置选择方法将返回的内容后调用,或者在设置选择fixture.detectChanges
后延迟第一个。这意味着fixture.detectChanges
从你的 beforeEach 中删除。
您很可能不需要异步或whenStable
为此工作。
推荐阅读
- laravel - 如何在模型本身的 Laravel 中将 unix 时间戳转换为 Carbon 实例?
- scala - 如何使用 Scala 在 Spark 数据框中为每个不同的列值创建行 ID 列
- ios - 使用什么 CIFilter 来获得扫描效果?
- wpf - 使用网格控件调整大小时应用程序内存迅速增加
- c# - Unity 的 GetComponent 通过字符串(或通过从另一个脚本传递的其他方法)
- c# - 如何为 WPF 应用程序和 ASP.net 应用程序创建安装程序?
- c++ - 从另一个程序检查 cin 而无需在 OSX 中等待
- javascript - 如何安全地跨域将表单从静态 html 站点提交到服务器端后端?
- file - 将具有特定文件名的文件从一个文件夹移动到另一个文件夹
- r - 在 R 中尝试子设置数据框