when trying to test my hapijs application "register" [1]: -- missing -- - node.js

I am using hapijs v17.2.3 . Also I am very new to hapi .I am trying to test my code using Lab a simple test utility for Node.js and code assertion library.
my test.js file is :
'use strict';
var path = require('path');
var dotEnvPath = path.resolve('./.env');
require('dotenv').config({ path: dotEnvPath });
const Code = require('code');
const Lab = require('lab');
const lab = exports.lab = Lab.script();
const describe = lab.describe;
const it = lab.it;
const expect = Code.expect;
const Joi = require('joi');
const Hapi = require('hapi');
const app = require('../app');
const server = new Hapi.Server();
const getServer = async () => {
const server = new Hapi.Server();
// server.connection();
return server.register(app)
.then(() => server);
};
lab.experiment('signup testing in "/signup"', () => {
lab.test('Return true if the user can successfully signup', (done, flags) => {
const signUpData = {
method: 'POST',
url: '/signup',
payload: {
name: 'vulcan',
password: 'vulcan#123',
email: 'vulcan#gmail.com',
username: 'vulcan123',
dob: '12-08-1994'
}
};
getServer()
.then((server) => server.inject(signUpData))
.then((response) => {
flags.note(`demo test note`);
if (response) {
console.log(response.statusCode);
Code.expect(response.statusCode).to.equal(201);
Code.expect(payload).to.contain(['name', 'password', 'email', 'username', 'dob']);
}
done();
});
});
});
lab.experiment('1) login test ', () => {
lab.test('login has successfully done', (done) => {
const loginData = {
method: 'POST',
url: '/login',
payload: {
email: 'wrong email',
login_password: 'wrong password',
}
};
getServer()
.then((server) => {
server.inject(loginData)
})
.then((response) => {
Code.expect(response.statusCode).to.equal(200);
done();
});
});
});
my test command is : lab --assert code --coverage -t 100
my signup controller is :
exports.postForm = {
description: 'Submit the signup page',
tags: ['api'],
notes: 'accepts name password verify and email',
auth: {
mode: 'try',
strategy: 'session'
},
validate: {
payload: {
name: Joi.string().required(),
password: Joi.string().min(4).max(20).required(),
verify: Joi.string().required(),
email: Joi.string().email().required(),
username: Joi.string().min(3).max(20).required(),
referredBy: Joi.any(),
dob: Joi.date().required().label('Date of Birth')
},
failAction: (request, h, error) => {
console.log('Validation Failed');
request.yar.flash('error', error.details[0].message.replace(/['"]+/g, ''));
return h.redirect('/signup').takeover();
}
},
handler: async (request, h) => {
try {
var user = {
name: request.payload.name,
password: request.payload.password,
email: request.payload.email,
username: request.payload.username.toLowerCase(),
referralName: request.payload.username + '#gg',
emailConfirmationToken: uuidv1(),
dob: request.payload.dob,
tnc: true
};
let data = await signupHelper.signUpUser(user, request);
if (data.statusCode === 201) {
if (request.payload.referredBy) {
let configureReferral = await signupHelper.configureReferral(request.payload.referredBy, data.userId);
if (configureReferral.statusCode === 200) {
request.yar.flash('success', 'Account created, Please Login');
return h.redirect('/login');
}
}
request.yar.flash('success', 'Account created, Please Login');
return h.redirect('/login');
} else {
request.yar.flash('error', data.message);
return h.redirect('/signup');
}
} catch (error) {
logger.error(error);
return h.redirect('/signup');
}
}
};
my login control :
exports.login = {
description: 'Post to the login page',
notes: 'Accepts two paramters email and password which got validation',
tags: ['api'],
auth: {
mode: 'try',
strategy: 'session'
},
plugins: {
crumb: {
key: 'crumb',
source: 'payload',
},
'hapi-auth-cookie': {
redirectTo: false
}
},
validate: {
payload: {
email: Joi.string().min(3).email().required(),
login_password: Joi.string().min(4).required()
},
failAction: (request, h, error) => {
request.yar.flash('error', error.details[0].message.replace(/['"]+/g, ''));
return h.redirect('/login').takeover();
}
},
handler: async (request, h) => {
try {
const next = request.query.next ? request.query.next : '/dashboard';
if (request.auth.isAuthenticated) {
return h.redirect(next);
}
let resultData = await loginHelper.findByCredentials(request.payload.email, request.payload.login_password);
if (resultData.statusCode === 200) {
request.cookieAuth.set(resultData.user);
return h.redirect(next);
} else {
request.yar.flash('error', resultData.message);
return h.redirect('/login');
}
} catch (error) {
logger.error(error);
request.yar.flash('error', error.message);
return h.redirect('/login');
}
}
};
this is the error when I run the test:
Socket server start initiated
Socket server started
Server started at https://127.0.0.1:8000
signup testing in "/signup"
✔ 1) Return true if the user can successfully signup (3615 ms)
1) login test
✖ 2) login has successfully done
(node:9708) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Invalid plugin options {
"plugin": {
"sock": {
"init": function (server, options) {\n
..........
..........
},
"register" [1]: -- missing --
}
}
[1] "register" is required
at new AssertionError (internal/errors.js:102:11)
at Object.exports.assert (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/node_modules/hoek/lib/index.js:517:11)
at Object.exports.apply (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/lib/config.js:22:10)
at internals.Server.register (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/lib/server.js:410:31)
at getServer (/home/jeslin/projects/hapi/gamergully/test/tests-signup.js:23:19)
at lab.test (/home/jeslin/projects/hapi/gamergully/test/tests-signup.js:115:9)
at Immediate.setImmediate [as _onImmediate] (/home/jeslin/projects/hapi/gamergully/node_modules/lab/lib/runner.js:628:31)
at runCallback (timers.js:810:20)
at tryOnImmediate (timers.js:768:5)
at processImmediate [as _immediateCallback] (timers.js:745:5)
(node:8764) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 6)
(node:8764) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Mongo Database connected
when I run only one test case, it wont return any error. If I run more
than one this error is showing
I have done this by following this link

This could be related to your server instance creation. In one test you are trying to create more than one server instance with the same configuration. That might be the problem I think. When I create tests, I am using lab.before and lab.beforeEach methods to create instances.
Here is a real-world test case from one of my projects.
const Lab = require('lab');
const lab = exports.lab = Lab.script();
const describe = lab.describe;
const it = lab.it;
const before = lab.before;
const after = lab.after;
const expect = require('code').expect;
// ..... other stufff
describe('Test Routes', () => {
let server;
before(async () => {
server = new Hapi.Server();
await server.register(app)
});
after(async () => {
await server.stop();
});
it('It should obtain valid response', async () => {
const qs = querystring.stringify(queryParams);
const res = await server.inject({
url: `/s?${qs}`,
method: 'get',
headers: {
"Cookie": "user=aighaeshaighaPopaGoochee8ahlei8x"
}
});
expect(res.statusCode).to.equal(200);
expect(res.result.userid).to.exist();
expect(res.result.status).to.equal(true);
// handle play action
const res2 = await server.inject({
url: `/b?id=${res.result.userid}`,
method: 'get'
});
expect(res2.statusCode).to.equal(200);
expect(res2.result.status).to.equal(true);
});
//
it('It should reject invalid request', async () => {
const res = await server.inject({
url: `/a?a=b&id=iChah3Ahgaaj2eiHieVeem6uw2xaiD5g`,
method: 'get'
});
expect(res.statusCode).to.equal(200);
expect(res.result.status).to.equal(false);
expect(res.result.message).to.equal("Invalid information");
});
// ... goes on
});
Just pay attention to before and after calls. I am creating only one instance of server then using it along side my test cases or use beforeEach and afterEach to isolate your instances, it's your choice.

Related

DiscordJS v14 - Command Handler

I'm trying to create a command handle function, and this is my code, however it gives me an error in the console.
Sometimes when I go and reload the bot, the error doesn't populate, but it won't show the slash command. Other times, I get the error listed below.
const chalk = require("chalk");
const fs = require("fs");
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
module.exports = (client) => {
client.handleCommands = async () => {
const commandFolders = fs.readdirSync("./src/commands");
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`./src/commands/${folder}`)
.filter((file) => file.endsWith(".js"));
const { commands, commandArray } = client;
for (const file of commandFiles) {
const command = require(`../../commands/${folder}/${file}`);
commands.set(command.data.name, command);
commandArray.push(command, command.data.toJSON());
console.log(
chalk.white("Command: ") +
chalk.cyan.bold`${command.data.name} ` +
chalk.white("has successfully loaded.")
);
}
}
const clientId = "(Client_ID)";
const rest = new REST({ version: "10" }).setToken(
process.env.DISCORD_DEV_TOKEN
);
try {
console.log("Started refreshing application (/) commands.");
await rest.put(Routes.applicationCommands(clientId), {
body: client.commandArray,
});
console.log("Successfully reloaded application (/) commands.");
} catch (error) {
console.error(error);
}
};
};
Here's the error.
DiscordAPIError[50035]: Invalid Form Body
0.name[BASE_TYPE_REQUIRED]: This field is required
at SequentialHandler.runRequest (/home/**/Discord Bot/node_modules/#discordjs/rest/dist/index.js:659:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (/home/**/Discord Bot/node_modules/#discordjs/rest/dist/index.js:458:14)
at async REST.request (/home/**/Discord Bot/node_modules/#discordjs/rest/dist/index.js:902:22)
at async Client.client.handleCommands (/home/**/Discord Bot/src/functions/handlers/handleCommands.js:35:7) {
requestBody: { files: undefined, json: [ [Object], [Object] ] },
rawError: {
code: 50035,
errors: { '0': [Object] },
message: 'Invalid Form Body'
},
code: 50035,
status: 400,
method: 'PUT',
url: 'https://discord.com/api/v10/applications/(Client_ID)/commands'
}
I've attempted to debug it and follow the documentation from the Discord.JS website, but that doesn't even resolve the issue.
I currently have just the typical ping command, and here's the code for that.
const { SlashCommandBuilder } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Return's the bot's ping!"),
async execute(interaction, client) {
const message = await interaction.deferReply({
fetchReply: true,
});
const newMessage = `API Latency: ${client.ws.ping}\n Client Ping: ${
message.createdTimestamp - interaction.createdTimestamp
}`;
await interaction.editReply({
content: newMessage,
});
},
};
Is anyone able to share where I'm making the mistake?
Turns out my issue was within commandArray.push.
I had it written out as
commandArray.push(command, command.data.toJSON());
When it needed to be
commandArray.push(command.data.toJSON());

Cypress automation test continuously generating authentication token while doing authentication test in SharePoint Sites

All the test is passing successfully but still the cypress test is generating token continuously.
cypress.config.js
const { defineConfig } = require("cypress");
const spauth = require("node-sp-auth");
let getLoginTest = async () => {
const username = "****#****.com";
const password = "******";
const pageUrl = "https://*****.sharepoint.com"
// Connect to SharePoint
const data = await spauth.getAuth(pageUrl, {
username: username,
password: password
});
return data;
};
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
// implement node event listeners here
on('task', {
// deconstruct the individual properties
async getLogin() {
try {
const res = await getLoginTest();
return res;
} catch (error) {
return error;
}
}
});
},
},
});
Below I have mentioned the tests case which I have created."Testspec.cy.js"
// <reference types="cypress" />
require('cypress-xpath')
describe('SharePoint Authentication', () => {
beforeEach(() => {
cy.task("getLogin").then(token => {
cy.visit({
method: "GET",
url: "https://*****.sharepoint.com/SitePages/Home.aspx",
headers: token.headers
});
});
});
it('SharePoint Authentication Test', () => {
cy.xpath('//*[contains(text(),"Customer Dashboard")]').should('be.visible');
cy.get('.alphabet > :nth-child(3)').click();
cy.contains('Leader').click();
});
});
Test Screen
Here is the screenshot of the cypress test

Keep getting the 'cannot set headers' with Axios on Firebase Functions which still fully executes regardless of the error

I have a Firebase function that executes on a Stripe webhooks via express. The function executes fine but the sending of the email (using Axios) keeps resulting in an error:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
It does work fine on localhost but the error appears when pushed to Firebase staging server. Weirdly the whole function executes fully including the Axios call where I'm getting the header issue (sending the email). It does take about 2-3 minutes to fully execute due to the error.
I've tried a number of different methods using return, and then() promises but it's still flagging this error. My code is as follows:
index.js
// Controllers
const stripeWebhookSubscription = require("./src/controllers/stripe/webhooks/subscription");
// Firebase
const admin = require("firebase-admin");
const functions = require("firebase-functions");
// Express
const express = require("express");
const cors = require("cors");
// Stripe
const stripe = require("stripe")(functions.config().stripe.key_secret);
const serviceAccount = require(functions.config().project.service_account);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: functions.config().project.database_url,
storageBucket: functions.config().project.storage_bucket,
});
const database = admin.firestore();
// -------------------------
// Stripe
// -------------------------
const stripeFunction = express();
stripeFunction.use(cors({origin: true}));
stripeFunction.post("/webhooks", express.raw({type: "application/json"}), (req, res) => {
const sig = req.headers["stripe-signature"];
let event;
try {
event = stripe.webhooks.constructEvent(
req.rawBody,
sig,
functions.config().stripe.webhook_secret
);
} catch (err) {
return res.status(400).send(`Webhook Error: ${err.message}`);
}
switch (event.type) {
case "customer.subscription.created":
stripeWebhookSubscription.createSubscription(database, event.data.object, res);
break;
(...)
default:
console.log(`Unhandled event type ${event.type}`);
break;
}
res.json({received: true});
});
exports.stripe = functions.https.onRequest(stripeFunction);
subscription.js
const functions = require("firebase-functions");
const stripe = require("stripe")(functions.config().stripe.key_secret);
const axios = require("axios");
class stripeWebhookSubscription {
static createSubscription(database, subscription, res) {
let barcode;
let plan;
let merchant;
let customer;
database.collection("subscriptions").add({
id: subscription.id,
customer: subscription.customer,
status: subscription.status,
price: {
amount: (subscription.items.data[0].price.unit_amount / 100).toFixed(2),
interval: subscription.items.data[0].price.recurring.interval,
interval_count: subscription.items.data[0].price.recurring.interval_count,
},
product: subscription.items.data[0].price.product,
created: subscription.created,
current_period_start: subscription.current_period_start,
current_period_end: subscription.current_period_end,
cancel_at: subscription.cancel_at,
cancel_at_period_end: subscription.cancel_at_period_end,
payment_gateway: "stripe",
current_usage: 1,
})
.then((doc) => {
barcode = doc.id;
return database.collection("plans").where("stripe.product", "==", subscription.items.data[0].price.product).limit(1).get();
})
.then((docs) => {
docs.forEach((doc) => {
return plan = doc.data();
});
})
.then(() => {
return database.collection("subscriptions").doc(barcode).set({
merchant: plan.merchant,
}, {merge: true});
})
.then(() => {
return database.collection("merchants").doc(plan.merchant).get();
})
.then((doc) => {
return merchant = doc.data();
})
.then(() => {
async function stripeCustomer() {
const stripeData = await stripe.customers.retrieve(subscription.customer);
customer = stripeData;
}
return stripeCustomer().then(() => {
return customer;
});
})
.then(() => {
return database.collection("customers").doc(subscription.customer).set({
name: customer.name,
email: customer.email,
phone: customer.phone,
delinquent: customer.delinquent,
created: customer.created,
livemode: customer.livemode,
merchant: plan.merchant,
subscriptions: [barcode],
}, {merge: true});
})
.then((doc) => {
return axios.request({
url: "https://api.sendinblue.com/v3/smtp/email",
method: "post",
headers: {
"api-key": functions.config().sendinblue.key,
"Content-Type": "application/json",
},
data: {
"to": [
{
"email": customer.email,
"name": customer.name,
},
],
"replyTo": {
"email": "support#scanable.com.au",
"name": "Scanable",
},
"templateId": 2,
"params": {
"plan_name": plan.name,
"interval_count": plan.interval_count,
"interval": plan.interval,
"subscription": barcode,
"merchant_name": merchant.name,
"merchant_email": merchant.email,
},
},
})
.then((response) => {
return console.log("Membership email sent to " + customer.email);
});
})
.then(() => {
res.status(200).send("✅ Subscription " + subscription.id + " created!");
})
.catch((err) => {
res.status(400).send("⚠️ Error creating subscription (" + subscription.id + "): " + err);
});
}
}
module.exports = stripeWebhookSubscription;
In index.js, you call this line:
stripeWebhookSubscription.createSubscription(database, event.data.object, res);
immediately followed by this line:
res.json({received: true});
By the time the createSubscription path has finished, the response has already been sent. When deployed to Cloud Functions, this will also terminate your function before it's done any of its workload (Note: this termination behaviour is not simulated by the local functions emulator).
Depending on what you are trying to achieve, you can probably just add the missing return to this line so that the res.json({received: true}) never gets called:
return stripeWebhookSubscription.createSubscription(database, event.data.object, res);
Additionally, on this line in subscription.js:
database.collection("subscriptions").add({
you need to add the missing return statement so the asynchronous tasks are properly chained:
return database.collection("subscriptions").add({

How do you mock Auth0 MangementClient using jest?

This is also a question on Auth0 node-auth0 library. The use case is that I am using the Auth0 create Actions API through Terraform and want to be able to writes tests against the Actions.
In this example I want to be able to test the onExecutePostLogin without using real values.
// auth0-post-login.js
exports.onExecutePostLogin = async (event, api) => {
const userId = event.user.user_id
const ManagementClient = require('auth0').ManagementClient
const management = new ManagementClient({
domain: event.secrets.domain,
clientId: event.secrets.clientId,
clientSecret: event.secrets.clientSecret,
audience: `https://${event.secrets.domain}/api/v2/`,
scope: 'read:users',
})
const params = { id: userId, page: 0, per_page: 50, include_totals: false }
let userPermissions = await management.getUserPermissions(params)
const map = require('array-map')
const permissions = map(userPermissions, function(permission) {
return permission.permission_name
})
api.accessToken.setCustomClaim('https://example.com/access', permissions.join(' '))
}
One of the main issues is that the functions like getUserPermissions is created through their utility wrapper:
utils.wrapPropertyMethod(ManagementClient, 'getUserPermissions', 'users.getPermissions');
This causes jest to have issues finding the functions.
I did something similar as stsmurf to mock the response of the Auth0 methods.
I have a file where I store my helper methods like "find a role by its name"
// helper.ts
import { ManagementClient } from 'auth0';
export const getRoleByName = async (roleName: string) => {
const api = new ManagementClient({
clientId: clientId,
clientSecret: clientSecret,
domain: domain,
});
const roles = await api.getRoles();
const role = roles.find((r) => r.name == roleName);
if (!role) throw new Error('Role not found');
return role;
};
// helper.test.ts
import { Role } from 'auth0';
import { getRoleByName } from './helpers';
const mockGetRoles = jest.fn();
jest.mock('auth0', () => {
return {
ManagementClient: jest.fn().mockImplementation(() => {
return {
getRoles: mockGetRoles,
};
}),
};
});
describe('Get role', () => {
beforeAll(() => {
const dummyRoles: Role[] = [
{ id: 'fake_id_1', description: 'Fake role nr 1', name: 'Fake Role 1' },
{ id: 'fake_id_2', description: 'Fake role nr 2', name: 'Fake Role 2' },
];
mockGetRoles.mockImplementation(() => dummyRoles);
});
it('can return a role if it exists', async () => {
const expectedResult: Role = {
id: 'fake_id_1',
description: 'Fake role nr 1',
name: 'Fake Role 1',
};
const result = await getRoleByName('Fake Role 1');
expect(expectedResult).toEqual(result);
});
it('will throw an error when a role is not found', async () => {
await expect(getRoleByName('Fake Role 3')).rejects.toThrowError();
});
});
In order to get to functions like getUserPermissions I needed to override the implementation of the ManagementClient. This allowed me to then define getUserPermissions as a mock function.
import { onExecutePostLogin } from './auth0-post-login'
const mockManagementClient = jest.fn()
const mockGetUserPermissions = jest.fn()
jest.mock('auth0', () => {
return {
ManagementClient: (opts) => {
mockManagementClient(opts)
return {
getUserPermissions: (params) => {
return mockGetUserPermissions(params)
},
}
},
}
})
describe('onExecutePostLogin', () => {
const mockSetCustomClaim = jest.fn()
beforeEach(() => {
mockSetCustomClaim.mockClear()
mockManagementClient.mockClear()
mockGetUserPermissions.mockClear()
mockGetUserPermissions.mockReturnValue([
{
permission_name: 'read:foo',
},
{
permission_name: 'update:bar',
},
])
})
const event = {
user: {
user_id: 'abcd123',
},
secrets: {
domain: 'test-example.us.auth0.com',
clientId: 'a-client-id',
clientSecret: 'a-client-secret',
},
}
const api = {
accessToken: {
setCustomClaim: mockSetCustomClaim,
},
}
it('initializes a ManagementClient', async () => {
await onExecutePostLogin(event, api)
expect(mockManagementClient).toHaveBeenCalledWith({
domain: event.secrets.domain,
clientId: event.secrets.clientId,
clientSecret: event.secrets.clientSecret,
audience: `https://${event.secrets.domain}/api/v2/`,
scope: 'read:users',
})
})
it('gets users permissions', async () => {
await onExecutePostLogin(event, api)
expect(mockGetUserPermissions).toHaveBeenCalledWith(
{ id: event.user.user_id, page: 0, per_page: 50, include_totals: false },
)
})
it('sets custom claims', async () => {
await onExecutePostLogin(event, api)
const expectedPermissions = 'read:foo update:bar'
expect(mockSetCustomClaim).toHaveBeenCalledWith(
'https://example.com/access', expectedPermissions,
)
})
})

cannot mock a fetch call with `fetch-mock-jest 1.5.1` lib

I'm trying to mock a fetch call using thisfetch-mock-jest but it the code still trys to go to the remote address and eventually fail with error message FetchError: request to https://some.domain.io/app-config.yaml failed, reason: getaddrinfo ENOTFOUND some.domain.io].
Here the the test code
import { AppConfig } from '#backstage/config';
import { loadConfig } from './loader';
import mockFs from 'mock-fs';
import fetchMock from 'fetch-mock-jest';
describe('loadConfig', () => {
beforeEach(() => {
fetchMock.mock({
matcher: '*',
response: `app:
title: Example App
sessionKey: 'abc123'
`
});
});
afterEach(() => {
fetchMock.mockReset();
});
it('load config from remote path', async () => {
const configUrl = 'https://some.domain.io/app-config.yaml';
await expect(
loadConfig({
configRoot: '/root',
configTargets: [{ url: configUrl }],
env: 'production',
remote: {
reloadIntervalSeconds: 30,
},
})
).resolves.toEqual([
{
context: configUrl,
data: {
app: {
title: 'Example App',
sessionKey: 'abc123',
},
},
},
]);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
function defer<T>() {
let resolve: (value: T) => void;
const promise = new Promise<T>(_resolve => {
resolve = _resolve;
});
return { promise, resolve: resolve! };
}
});
loadConfig has the fetch code that I'm trying to mock.
export async function loadConfig(
options: LoadConfigOptions,
): Promise<AppConfig[]> {
const loadRemoteConfigFiles = async () => {
const configs: AppConfig[] = [];
const readConfigFromUrl = async (remoteConfigProp: RemoteConfigProp) => {
const response = await fetch(remoteConfigProp.url);
if (!response.ok) {
throw new Error(
`Could not read config file at ${remoteConfigProp.url}`,
);
}
remoteConfigProp.oldETag = remoteConfigProp.newETag ?? undefined;
remoteConfigProp.newETag =
response.headers.get(HTTP_RESPONSE_HEADER_ETAG) ?? undefined;
remoteConfigProp.content = await response.text();
return remoteConfigProp;
};
.......
return configs;
}
let remoteConfigs: AppConfig[] = [];
if (remote) {
try {
remoteConfigs = await loadRemoteConfigFiles();
} catch (error) {
throw new Error(`Failed to read remote configuration file, ${error}`);
}
}
........ do some stuff with config then return
return remoteConfigs;
}
The config is a yaml file, that eventually gets parsed and converted into config object.
Any idea why is it failing to mock the fetch call?
replaced
import fetchMock from 'fetch-mock-jest';
with
const fetchMock = require('fetch-mock').sandbox();
const nodeFetch = require('node-fetch');
nodeFetch.default = fetchMock;
and fetchMock.mockReset(); with fetchMock.restore();

Resources