简体   繁体   English

在 Angular 中模拟静态导入的类

[英]Mock statically imported class in Angular

I am using facebook SDK in my Angular application for which I am importing the FB SDK class like below我在我的 Angular 应用程序中使用 facebook SDK,我正在为其导入 FB SDK 类,如下所示

import MiniAppSDKClient from 'src/clients/MiniAppSDKClient';

After this I am using below method of that class to get some information在此之后我使用该类的以下方法来获取一些信息

  ngOnInit(): void {
    // Get data from Facebook SDK
    const entryPointData = MiniAppSDKClient.getEntryPointData();
  }

During testing I want to mock the getEntryPointData method of that class.在测试期间,我想模拟该类的getEntryPointData方法。 Can't find any way to mock above class or that particular method of that class.找不到任何方法来模拟上面的类或该类的特定方法。 Any help is appreciated.任何帮助表示赞赏。

Thank you!谢谢!

The right way is to update the code so MiniAppSDKClient should be injected.正确的方法是更新代码,以便注入MiniAppSDKClient

However, if you cannot change the code, you can use beforeEach and afterEach like that:但是,如果您无法更改代码,则可以像这样使用beforeEachafterEach

describe('suite', () => {
  let getEntryPointDataBackup;

  beforeEach(() => getEntryPointDataBackup = MiniAppSDKClient.getEntryPointData);
  afterEach(() => MiniAppSDKClient.getEntryPointData = getEntryPointDataBackup);

  // your normal beforeEach here.

  it('test', () => {
    MiniAppSDKClient.getEntryPointData = () => myMockEntryPointData;

    // the rest of your code.
  });
});

The right way正确的方式

create a root token which provides MiniAppSDKClient and simply mock it in TestBed:创建一个提供MiniAppSDKClient的根令牌,并在 TestBed 中简单地模拟它:

export const MINI_APP_SDK_CLIENT = new InjectionToken('MINI_APP_SDK_CLIENT', {
  factory: () => MiniAppSDKClient,
  providedIn: 'root',
});

Your component / directive / service should use DI:你的组件/指令/服务应该使用 DI:

class TargetComponent implements OnInit {
  constructor(@Inject(MINI_APP_SDK_CLIENT) client: typeof MiniAppSDKClient) {}

  ngOnInit(): void {
    // Get data from Facebook SDK
    const entryPointData = this.client.getEntryPointData();
  }
}

its test:它的测试:

describe('suite', () => {
  beforeEach(() => TestBed.configureTestingModule({
    declarations: [TargetComponent],
    providers: [{
      provide: MINI_APP_SDK_CLIENT,
      useValue: {
        getEntryPointData: () => {
          return myFakeEntryPointData;
        },
      },
    }],
  }).compileComponents());
});

Profit!利润!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM