测试和模拟玩笑的电话无法正常工作

时间:2019-10-24 05:31:55

标签: reactjs jestjs

我正在尝试测试以下功能:

// playlist.js
export function getSimplePlaylist() {
  // something here
}

export function getPlaylist(type, settings) {
  let options = { type };

  if (type === 'simple') {
    options.getData = () => {
      const { videos } = settings;
      return getSimplePlaylist(videos);
    };
  }
   // There are few more cases here, but no need to post them
 return options;
}

我尝试了多种不同的测试方法,但是没有运气,即:

//playlist.spec.js
import * as playlist from '.';
describe('getPlaylist', () => {
  beforeEach(() => {
    jest.resetAllMocks();
  });

  it('should get correct option when static ', () => {
    playlist.getSimplePlaylist = jest.fn();
    const videos = playlist.getPlaylist('simple', { videos: [1, 2, 3] });
    videos.getData()
    expect(playlist.getSimplePlaylist).toBeCalled();
  });
});

关于如何测试上述内容的任何想法?谢谢!

2 个答案:

答案 0 :(得分:0)

如果以这种方式使用函数,则可以使用JS函数编程。 getPlayList将始终称为原始getSimplePlaylist。如果要执行此操作,则应使用class:

class Playlist {
  def() {
    return 'def';
  }

  abc(cond) {
    if (cond) {
      return this.def();
    }
  }
}

export default Playlist;

然后您可以对其进行测试:

import Playlist from './playlist';

describe('Name of the group', () => {
  it('should ', () => {
    const play = new Playlist();
    play.def = jest.fn().mockReturnValue('mock');
    expect(play.abc(true)).toEqual('mock');
    expect(play.def).toBeCalled();
  });
});

或者您可以将函数与默认实现一起使用,然后在测试中通过附加参数:

// playlist.js
export function getSimplePlaylist() {
  // something here
}

export function getPlaylist(type, settings, simplePlaylistFunc=getSimplePlaylist) {
  let options = { type };

  if (type === 'simple') {
    options.getData = () => {
      const { videos } = settings;
      return simplePlaylistFunc(videos);
    };
  }
   // There are few more cases here, but no need to post them
 return options;
}

答案 1 :(得分:0)

这里模拟文件中函数的最简单解决方案可能是不单独导出它们,而是从对象中导出并在特定模块中从该对象中使用它

// playlist.js
function getSimplePlaylist() {
  // something here
}

function getPlaylist(type, settings) {
  let options = { type };

  if (type === 'simple') {
    options.getData = () => {
      const { videos } = settings;
      return funcs.getSimplePlaylist(videos);
    };
  }
   // There are few more cases here, but no need to post them
 return options;
}

const funcs = {
    getSimplePlaylist,
    getPlaylist
}

export default funcs;

现在您可以像测试它们一样

//playlist.spec.js
import playlist from '.';
describe('getPlaylist', () => {
  beforeEach(() => {
    jest.resetAllMocks();
  });

  it('should get correct option when static ', () => {
    playlist.getSimplePlaylist = jest.fn();
    const videos = playlist.getPlaylist('simple', { videos: [1, 2, 3] });
    videos.getData()
    expect(playlist.getSimplePlaylist).toBeCalled();
  });
});