Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何使用jest.mock方式来代理实际模块中函数调用 #1

Open
SuAutumn opened this issue Jun 23, 2020 · 0 comments
Open

如何使用jest.mock方式来代理实际模块中函数调用 #1

SuAutumn opened this issue Jun 23, 2020 · 0 comments

Comments

@SuAutumn
Copy link
Owner

在使用jest框架编写自动化测试的时候,我们的项目常常需要和后端获取数据之后才能测试之后的逻辑。但这往往是不方便的,也比较依赖后台的接口是否正常。

所以jest提供了一个方式jest.mock可以代理这些真实的api接口进行模拟测试。

这里我以jest官方示例为

// __test__/user.test.js
'use strict';

/**
 * jest.mock: (moduleName: string, moduleFunction?: () => unknow) => Jest
 * 如果根目录下面没有提供__mocks__/request.js 则request为undefined
 */
jest.mock('../request'); // mock request 模块

import * as user from '../user';

// Testing promise can be done using `.resolves`.
it('works with resolves', () => {
  expect.assertions(1);

  // 此时user.getUserName中request方法调用为__mocks__/request.js中的方法
  return expect(user.getUserName(5)).resolves.toEqual('Paul');
});

但是在实际使用过程中我的api文件可能不在根目录下,这个时候的仅仅一个jest.mock(moduleName)就无法正常工作了,这个时候我需要多添加一个具体实现方法,如下:

'use strict';

jest.mock('../api/request', () => {
  /**
   * 此为一个独立模块,不能再引入另外scope
   * 这是此模块所有函数能访问top scope
   */
  
  const users = {
    4: {name: 'Mark'},
    5: {name: 'Paul'},
  };
  return {
    __esModule: true, // 必要,表面这是个模块
    default: jest.fn(url => { // 等同于export default
      return new Promise((resolve, reject) => {
        const userID = parseInt(url.substr('/users/'.length), 10);
        process.nextTick(() =>
          users[userID]
            ? resolve(users[userID])
            : reject({
              error: 'User with ' + userID + ' not found.',
            }),
        );
      });
    })
  }
});

import * as user from '../user';

// Testing promise can be done using `.resolves`.
test('works with resolves', () => {
  expect.assertions(1);
  return expect(user.getUserName(5)).resolves.toEqual('Paul');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant