【发布时间】:2020-05-21 14:54:32
【问题描述】:
我正在尝试测试一些依赖于返回一些数据的 api 的代码。目前,我可以在这个函数中模拟 listNamespacedIngress 的调用:
async function getIngress(namespace) {
try {
const result = await k8sIngressApi.listNamespacedIngress(namespace, true);
const resultSpec = result.body.items.filter(e => e.metadata.name === deploymentPrefix)[0];
if (!resultSpec) {
throw new TypeError('Ingress spec is undefined');
}
return resultSpec;
} catch (e) {
return Promise.reject(e);
}
}
在这个库中使用 jest.mock 并模拟该函数的返回值,如下所示:
jest.mock('@kubernetes/client-node', () => ({
KubeConfig: jest.fn().mockImplementation(() => ({
loadFromCluster: jest.fn(),
loadFromDefault: jest.fn(),
makeApiClient: () => ({
listNamespacedIngress: () =>
Promise.resolve({
body: {
items: [
{
metadata: {
name: 'a',
namespace: 'b',
},
spec: {
rules: [
{
host: 'url.com',
http: {
paths: [
{
backend: {
serviceName: 'a',
servicePort: 80,
},
},
],
},
},
],
},
},
这样,如果 resultSpec 没有最终未定义,我可以测试初始返回值,如下所示(此测试通过):
it('Should return storybook-staging ingress details', async () => {
// When
const result = await getIngress();
// Then
expect(result.metadata.name).toEqual('a');
});
但是,我不确定如何强制 listNamespacedIngress 返回未定义?
编辑:添加了对模块的充分利用
const kc = new k8s.KubeConfig();
kc.loadFromDefault();
const k8sDeploymentApi = kc.makeApiClient(k8s.AppsV1Api);
const k8sServiceApi = kc.makeApiClient(k8s.CoreV1Api);
const k8sIngressApi = kc.makeApiClient(k8s.NetworkingV1beta1Api);
const BRANCH_NAME = process.argv.slice(2)[0].toLowerCase();
const NAMESPACE = 'dev';
const deploymentPrefix = 'storybook-staging';
const DEPLOYMENT_CONFIG = getDeploymentConfig(deploymentPrefix, BRANCH_NAME);
const SERVICE_CONFIG = getServiceConfig(deploymentPrefix, BRANCH_NAME);
const INGRESS_CONFIG = getIngressConfig(deploymentPrefix);
const HTTP_CONFLICT = 409;
process.on('exit', code => {
console.log(`About to exit with code: ${code}`);
});
async function getIngress(namespace) {
try {
const result = await k8sIngressApi.listNamespacedIngress(namespace, true);
console.log(result);
const resultSpec = result.body.items.filter(e => e.metadata.name === deploymentPrefix)[0];
if (!resultSpec) {
throw new TypeError('Ingress spec is undefined');
}
return resultSpec;
} catch (e) {
return Promise.reject(e);
}
}
【问题讨论】:
标签: javascript node.js unit-testing mocking jestjs