要解决Angular Spectator的setInput对非字符串输入无效的问题,可以使用jasmine的spyOnProperty方法来模拟输入属性,并使用Angular的ChangeDetectorRef来手动触发变更检测。
以下是一个示例代码:
import { Spectator, createComponentFactory } from '@ngneat/spectator';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let spectator: Spectator;
const createComponent = createComponentFactory(MyComponent);
beforeEach(() => {
spectator = createComponent();
});
it('should update input property with non-string value', () => {
// 使用spyOnProperty方法模拟输入属性
spyOnProperty(spectator.component, 'myInput', 'set').and.callThrough();
// 设置非字符串输入值
spectator.setInput('myInput', 123);
// 手动触发变更检测
spectator.detectChanges();
expect(spectator.component.myInput).toBe(123);
});
});
在这个示例中,我们使用spyOnProperty
方法来模拟myInput
属性的setter方法,并调用callThrough
以确保实际的setter方法被调用。然后,我们使用setInput
方法将非字符串值设置给myInput
属性。最后,我们手动调用detectChanges
方法来触发变更检测,以便更新组件的输入属性。
通过这个解决方法,我们可以在Angular Spectator中有效地设置非字符串的输入属性。