0

如何根据测试更改模拟的实现。

这是我试图单元测试的代码。

open(url: string, target: string = '_self'): void {
 const win = this.document.defaultView?.open(url, target);
 win?.focus();
}

在我的单元测试之下

const MockDocument = {
  location: { replace: jest.fn() },
  defaultView: undefined
};

const createService = createServiceFactory({
  service: RedirectService,
  providers: [
   { provide: DOCUMENT, useValue: MockDocument }
 ]
});

我的策略是在第一次测试时将 defaultView 设置为undefined。在下一个测试中,我将更改实现以包含 open 函数,如下所示

const defaultView = {
open: jest
  .fn()
  .mockImplementation((url: string, target: string = '_self') => {
    url;
    target;
    return { focus: jest.fn().mockImplementation(() => {}) };
  })
};

const MockDocument = {
 location: { replace: jest.fn() },
 defaultView: defaultView
};

如何根据测试更改实现?

感谢您的帮助

编辑

it('should not call "open" if defaultView is not truthy', () => {
  spectator.service.openFocus('foo');

  expect(mockDocument.defaultView).not.toBeTruthy();
});

it('should call "open" if defaultView is truthy', () => {
  //CHANGE THE IMPLEMENTATION HERE...
  const spy = jest.spyOn(mockDocument.defaultView, 'open')

  spectator.service.openFocus('foo');

  expect(spy).toHaveBeenCalled();
});
4

1 回答 1

0

您可以将 defaultView 设置为变量并更改变速测试。

let defaultView: any;

const MockDocument = {
    location: { replace: jest.fn() },
    defaultView};

beforeEach(() => {
    ...
});

it('should not call "open" if defaultView is not truthy', () => {
    defaultView = undefined;
    expect(mockDocument.defaultView).not.toBeTruthy();
});

it('should call "open" if defaultView is truthy', () => {
    defaultView = {
        open: jest
        .fn()
        .mockImplementation((url: string, target: string = '_self') => {
            url;
            target;
            return { focus: jest.fn().mockImplementation(() => {}) };
        })
    };

    const spy = jest.spyOn(mockDocument.defaultView, 'open')

    expect(spy).toHaveBeenCalled();
});
于 2021-08-04T20:37:30.980 回答