Reputation: 3002
Totally new to GCP functions. Trying to test out the functions and code written in the file to make sure it doesn't revert. Include the index.js file in the test file does not provide access to the functions in the file however and I can't figure out how I can test these.
For a simple example I have a function that is just a helper converting the date object because we need to format it a specific way. The function in the GCP Function file is called formatDateValue
.
I want to write a test that just sends a string there and verifies the expected return. But it keeps telling me that formatDateValue
is undefined.
I tried to export it from index.js like this: exports.formatDateValue = formatDateValue;
, but that didn't change anything.
The file in reference to the test file is at ../index.js
and it is required in the test file.
What do I have to do to access this function to test it?
function code (other functions just left out to save on space)
index.js
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [START functions_hello_bigquery]
// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();
const functions = require('@google-cloud/functions-framework');
const mysql = require('mysql');
const crypto = require("crypto");
// We need these in the global scope of this file
var hasError = false;
const currentSyncDbDateValue = new Date();
/**
*
* Helper functions that could be moved into some kind of util area
*
*/
// The challenge here is toISOString converts the time by adding on 5 hours.
function formatDateValue(dateStr, date) {
let formattedDate;
if(date != null) {
const dateArr = dateStr.split(' ');
const year = dateArr[3]; // Format: 2022
const day = dateArr[2]; // Format: 15, 02
const time = dateArr[4]; // Format: 15:17:42
const month = date.toISOString().split('-')[1]; // Format: 09 - We need to get the month from this, but NOT THE TIME
formattedDate = `${year}-${month}-${day} ${time}`
} else {
formattedDate = null;
}
return formattedDate;
}
...
/**
* HTTP Cloud Function that returns BigQuery query results
*
* @param {Object} req Cloud Function request context.
* @param {Object} res Cloud Function response context.
*/
functions.http('assetSync', async (req, res) => {
// Get the tenantId from the req params
const tenantId = `${req.query.tenantId}`;
// Get the new asset sync date
const currentSync =
currentSyncDbDateValue.toISOString().replace(/T/, ' ').replace(/\..+/, ''); // replace T with a space, delete the dot and everything after to format the date correctly for the queries
// returns the last asset sync date formatted, or null if this is the first sync
const lastAssetSync = await getLastAssetSync(tenantId).then((value) => {return value;});
try {
// This is the query to create new lists in the DB. Returns either the query string or null
const newListQueryStr = await getNewListsQueryStr(tenantId, currentSync, currentSyncDbDateValue, lastAssetSync);
const lastAssetSyncQueryStr = await getLastAssetSyncQueryStr(tenantId, currentSync);
const queriesArr = buildQueriesArr([newListQueryStr, lastAssetSyncQueryStr]);
const transactionStatus = runTransaction(queriesArr, res);
res.status(200).send(`Transactions have run successfully`);
} catch (err) {
console.error("ERROR : " + err);
res.status(500).send(`Error querying BigQuery: ${err}`);
}
});
exports.formatDateValue = formatDateValue;
test.js
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const supertest = require('supertest');
const {getTestServer} = require('@google-cloud/functions-
framework/testing');
require('../index.js');
describe('Creates correct Dates', () => {
it('constructs the correct date format', async () => {
const dateStr = 'Fri Sep 16 2022 15:17:42 GMT-0500 (Central Daylight Time)'; // Current test asset sync value
const formattedDateStr = formatDateValue(currentTestSync);
const expectedFormattedDateStr = '2022-09-16 15:17:42';
assert.equal(formattedDateStr, expectedFormattedDateStr);
})
})
Upvotes: 2
Views: 268
Reputation: 3767
To solve this you have to export the function in index.js file like this:
exports.formatDateValue = formatDateValue;
Then you can import it into the test file like this:
const {formatDateValue} = require('../index.js');
Upvotes: 2