【问题标题】:Original value being updated by injector in test测试中注入器更新的原始值
【发布时间】:2020-10-19 20:24:21
【问题描述】:

我正在尝试测试我的一种可注射组件。我正在使用提供者给它一个模拟值APP_CONFIG。这是组件的样子:

export let APP_CONFIG = new InjectionToken<any>('app.config');

@Injectable()
export class ConfigService {

   private readonly config;

   constructor(private injector: Injector) {
      this.config = this.injector.get(APP_CONFIG);
   }


   public update(): void {
      this.config.context = 'some value'
   }

   public get config(): any {
     return this.config
   }
}

这就是测试设置的样子:

const CONFIG = { context: 'cat' };

beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [
            ConfigService,
            { provide: APP_CONFIG, useValue: CONFIG },
        ]
    });

    service = TestBed.inject(AppConfigService);
});

我遇到的问题是,当 this.config = 'some value' 出现在 update 方法中时,它会在我的测试中更新 CONFIG 对象中的原始引用。这导致我的测试出现问题,因为我无法正确检查 this.config 是否已更改,因为它始终等于 CONFIG

例如:

it('provides updated config after update', () => {
   const result: any = service.config;
   // CONFIG is currently {context: 'cat'}
   service.update();
   // Once service.update() occurs CONFIG gets changed to {context: 'some value'} and the following test fails as a result. I expect it to pass because result should be different from the original reference.
   expect(result).not.toEqual(CONFIG);
})

因此,这会导致任何其他出于比较原因导入 CONFIG 对象的后续测试因相同原因而失败。

我可以做些什么来防止这种回归吗?这在从 Angular 8 升级到 9 后开始发生,所以我不确定是否有一些内部变化会改变它的工作方式。

【问题讨论】:

    标签: javascript angular jasmine karma-jasmine


    【解决方案1】:

    看起来您只是在传递相同的引用并将其与自身进行比较。您需要克隆原始对象。

    imo 最简单的方法是使用扩展运算符:

    { provide: APP_CONFIG, useValue: ...CONFIG },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多