模拟 BsModalRef 进行单元测试

G.S*_*pal 7 unit-testing typescript karma-jasmine ngx-bootstrap angular5

我正在使用 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);
    });
  });
Run Code Online (Sandbox Code Playgroud)

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

Jus*_*bel 5

我最近不得不做类似的事情,并且 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

    });
});
Run Code Online (Sandbox Code Playgroud)

只要您按如下方式调用 bsModal,这种方法就会起作用

let bsModalRef = this.modalService.show(MyChannelModalComponent));
Run Code Online (Sandbox Code Playgroud)

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