我仍在学习如何使用 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/