我有一组便捷的apiHelpers。函数之一是axios的get方法包装,该包装称为getWrapper
const getWrapper = (url) => (
(endpoint, headers={}) => (
axios.get(
`${url}${endpoint}`,
{headers: { ...getHeaders(), ...headers }}
)
)
);
对于未经身份验证的呼叫,我有一个getUnauthenticatedApiHelper
函数,该函数调用getWrapper
。 getWrapper
做一些事情,其中之一是将提供的端点连接到BASE_URL
这是一个环境变量。
export const getUnauthenticatedApiHelper = (endpoint, headers) => getWrapper(BASE_URL)(endpoint, headers);
我的测试调用getUnauthenticatedApiHelper,并期望它随后调用getWrapper。
describe('apihelpers', () => {
test('getUnauth', () => {
const getWrapper = jest.fn();
var wtf = getUnauthenticatedHelper('end/point/');
console.log(wtf);
expect(getWrapper).toHaveBeenCalled();
});
});
注销结果时,可以看到端点已与BASE_URL
正确连接,但是我的测试失败,并显示错误Expected mock function to have been called, but it was not called.
这是否是一项有效的测试,不在atm重点之内,因为我只是想了解如何有效使用笑话。我已经在网上代表中对此进行了试验-不管我做什么,我一直遇到getWrapper
不被调用的问题,这使我相信jest.fn有一些根本性的误解( )-那么我想念的是什么?应该如何测试getWrapper
被称为?
Here is an online repl是我一直在尝试的内容
答案 0 :(得分:0)
我使您的演示作品成功了,您可以在这里查看:https://repl.it/repls/IllStandardDesigner
getWrapper.js
:
function getWrapper(url) {
return (endpoint, headers={}) => (
`${url}${endpoint}`
);
}
module.exports = getWrapper
getUnauthenticatedHelper.js
:
const getWrapper = require('./getWrapper');
const BASE_URL = 'foo/';
const getUnauthenticatedHelper = (endpoint, headers) => getWrapper(BASE_URL)(endpoint, headers);
module.exports = getUnauthenticatedHelper
单元测试:
const add = require('./add');
const getWrapper = require('./getWrapper');
const getUnauthenticatedHelper = require('./getUnauthenticatedHelper');
describe('add', () => {
it('should add two numbers', () => {
expect(add(1, 2)).toBe(3);
});
});
jest.mock('./getWrapper', () => {
return jest.fn((url) => {
return (endpoint, headers = {}) => (
`${url}${endpoint}`
);
})
})
describe('apihelpers', () => {
test('getUnauth', () => {
var wtf = getUnauthenticatedHelper('end/point/');
console.log(wtf);
expect(getWrapper).toHaveBeenCalled();
});
});
单元测试结果:
Jest v24.9.0 node v10.16.3 linux/amd64
jest --colors --config /home/runner/config.json
PASS ./add-test.js
add
✓ should add two numbers (5ms)
apihelpers
✓ getUnauth (57ms)
console.log add-test.js:22
foo/end/point/
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 2.788s
Ran all test suites.