【问题标题】:Mocking BsModalRef for Unit Testing模拟 BsModalRef 进行单元测试
【发布时间】:2018-10-19 07:44:43
【问题描述】:

我正在使用 BsModalRef 来显示模式并使用 content 属性发送数据。所以我们有一些这样的:

this.followerService.getFollowers(this.bsModalRef.content.channelId).subscribe((followers) => {
    this.followerList = followers;
    this.followerList.forEach((follower) => {
      follower.avatarLink = this.setUserImage(follower.userId);
      this.followerEmails.push(follower.email);
    });
  });

我们正在 bsModalRef (this.bsModalRef.content.channelId) 的内容中设置 channelId。它工作正常。现在我正在为此编写一个单元测试。问题是我无法模拟它。我尝试过覆盖、间谍等,但似乎没有任何效果。我正在使用link 中提到的方法。一种替代方法是使用 TestBed,但我不太了解它的用途。谁能帮我找到可以实现这一目标的任何方法?

【问题讨论】:

    标签: unit-testing typescript karma-jasmine angular5 ngx-bootstrap


    【解决方案1】:

    我最近不得不做一些类似的事情,并且 Mocking 方法调用起作用了。棘手的部分是在测试套件和组件中注入 BsModalService。

    describe('MyFollowerService', () => {
        configureTestSuite(() => {
            TestBed.configureTestingModule({
                imports: [...],
                declarations: [...],
                providers: [...]
            }).compileComponents();
        });
    
        // inject the service
        beforeEach(() => {    
            bsModalService = getTestBed().get(BsModalService);
        }
    
    
        it('test', () => {
           // Mock the method call 
           bsModalService.show = (): BsModalRef => {
               return {hide: null, content: {channelId: 123}, setClass: null};
           };
    
           // Do the test that calls the modal
    
        });
    });
    

    只要您按以下方式调用 bsModal,这种方法就可以工作

    let bsModalRef = this.modalService.show(MyChannelModalComponent));
    

    最后,这里有一些链接更深入地介绍了使用 TestBed 设置测试。

    【讨论】:

      猜你喜欢
      • 2018-09-04
      • 2013-11-12
      • 2018-11-21
      • 2013-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 2020-04-06
      相关资源
      最近更新 更多