簡體   English   中英

在測試中由注入器更新的原始值

[英]Original value being updated by injector in test

我正在嘗試測試我的可注射組件之一。 我正在使用提供程序為其提供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'時,它會在我的測試中更新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 之后開始發生的,所以我不確定是否在引擎蓋下進行了一些更改來改變它的工作方式。

看起來您只是在傳遞相同的引用並將其與自身進行比較。 您需要克隆原始對象。

imo 最簡單的方法是使用擴展運算符:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM