node.js - 开 Jest ,不要 mock request-promise-native post 方法

标签 node.js jestjs

我仍在学习如何使用 jest,但我对为什么会遇到这个问题感到困惑。

基本上,我想模拟我正在测试的函数中使用的 request-promise-native 中的 post 方法,但由于某种原因我没有这样做知道 spy /模拟没有被传递到声明的函数,因此测试失败。

源文件定义如下:

const request = require('request-promise-native')
const recaptcha = {
  endpoint: 'https://www.google.com/recaptcha/api/siteverify',
  secretKey: process.env['RECAPTCHA_SECRET_KEY'] || null
}

class ReCaptcha {
  /**
   * Verifies the captcha token response
   * @param {String} response - The client token response
   * @returns {Promise<Boolean>} - Whether the captcha token is valid
   */
  static async verify (response) {
    const requestOptions = {
      url: recaptcha.endpoint,
      qs: {
        secret: recaptcha.secretKey,
        response
      },
      json: true
    }

    const data = await request.post(requestOptions)

    return data.success
  }
}

module.exports = ReCaptcha

测试文件定义如下:

const request = require('request-promise-native')
const ReCaptcha = require('./../../../serverless/lib/ReCaptcha')

describe('Lib - ReCaptcha test', () => {

  afterEach(() => {
    jest.resetAllMocks()
  })

  it('should request captcha verification', async () => {
    const value = 'foo'
    const expected = true

    jest.spyOn(request, 'post').mockResolvedValue({ success: true })

    const result = await ReCaptcha.verify(value)

    expect(result).toEqual(expected)
    expect(request.mock.calls[0][0]).toHaveProperty('qs.response', value)
  })
})

该函数的结果为 false,这是由于 request 从 google 获得的响应,这使得模拟似乎无法正常工作。

我在执行测试时调试了请求对象中的值,发现 post 方法在测试文件中被模拟,而在源文件中却没有。

注意:我也尝试过使用jest.mock,但结果仍然相同。

最佳答案

您可以像这样手动模拟 request-promise-native 模块和 post 方法:

jest.mock('request-promise-native', () => {
  return {
    post: jest.fn()
  };
});

const request = require('request-promise-native');
const ReCaptcha = require('.');

describe('Lib - ReCaptcha test', () => {
  afterEach(() => {
    jest.resetAllMocks();
  });

  it('should request captcha verification', async () => {
    const value = 'foo';
    const expected = true;

    const postSpy = jest.spyOn(request, 'post').mockResolvedValue({ success: true });

    const result = await ReCaptcha.verify(value);

    expect(result).toEqual(expected);
    expect(postSpy).toBeCalledWith({
      url: 'https://www.google.com/recaptcha/api/siteverify',
      qs: { secret: null, response: 'foo' },
      json: true
    });
  });
});

单元测试结果:

 PASS  src/stackoverflow/57416715/index.spec.js
  Lib - ReCaptcha test
    ✓ should request captcha verification (6ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.591s

关于node.js - 开 Jest ,不要 mock request-promise-native post 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57416715/

相关文章:

javascript - 如何在没有 Node.JS 的情况下最小化 Angular 的打包?

javascript - NOT 在 Node/ Mongoose 中不起作用

javascript - 如何使用 Enzyme/Jest 测试 ComponentWillMount 中的逻辑

reactjs - React jest testing Google Maps Api,Uncaught TypeError : this. autocomplete.addListener 不是函数

node.js - 在 Windows 10 WSL 上访问 AWS 凭证 : Error: connect ECONNREFUSED 169. 254.169.254 :80 at TCPConnectWrap. afterConnect

node.js - Elasticsearch对多个查询进行排序

javascript - 处理Node js中的多个错误

javascript - 尝试使用 Jest 测试 JS 类时出错

reactjs - 将 Jest 与 react-scripts 一起使用(通过 yarn 运行),如何在不必传递 watchAll 标志的情况下获得完整的覆盖率报告?

reactjs - jest.mock(module) 和 jest.fn() 有什么区别