你用
request(...)
而不是使用
request.post(...)
request
功能不可用
request.post
方法。
例如。
a.js
:
const request = require('request-promise');
module.exports = async () => {
var options = {
uri: 'fsdsfd',
headers: {
'content-type': 'application/json',
},
body: {
A: 'A',
B: 'B',
},
json: true,
};
try {
const selectResult = await request.post(options);
return selectResult;
} catch (err) {
return err;
}
};
a.test.js
:
const request = require('request-promise');
const moduleA = require('./a');
jest.mock('request-promise', () => {
return {
post: jest.fn(),
};
});
describe('59261385', () => {
afterEach(() => {
jest.resetAllMocks();
});
test('Update function', async () => {
request.post.mockResolvedValueOnce({ result: [] });
const actual = await moduleA();
expect(actual).toEqual({ result: [] });
expect(request.post).toBeCalledWith({
uri: 'fsdsfd',
headers: {
'content-type': 'application/json',
},
body: {
A: 'A',
B: 'B',
},
json: true,
});
});
});
单元测试结果及覆盖率报告:
PASS src/stackoverflow/59261385/a.test.js (11.669s)
59261385
â Update function (33ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 87.5 | 100 | 100 | 83.33 | |
a.js | 87.5 | 100 | 100 | 83.33 | 20 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 13.599s
https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59261385
更新:
你可以用
jest.spyOn
答。测试.js
:
const request = require('request-promise');
const moduleA = require('../a');
describe('59261385', () => {
afterEach(() => {
jest.restoreAllMocks();
});
test('Update function', async () => {
const postSpy = jest.spyOn(request, 'post').mockResolvedValueOnce({ result: [] });
const actual = await moduleA();
expect(actual).toEqual({ result: [] });
expect(postSpy).toBeCalledWith({
uri: 'fsdsfd',
headers: {
'content-type': 'application/json'
},
body: {
A: 'A',
B: 'B'
},
json: true
});
});
});
代码沙盒:
https://codesandbox.io/s/jestjs-jgye4