Getting this error while testing my Ebay Contract
ITs An Ebay Smart Contract Where Products are being Auctioned
yarn run v1.22.15
warning package.json: No license field
$ "E:\Block Chain Projects\30_SMARTCONTRACTS.sol\A Way To Testing\node_modules\.bin\hardhat" test
Ebay Smart Contract
Upload Product function
This is deployer0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266
1) "before each" hook for "if the base Price is less than 0 or invalid should revert"
0 passing (2s)
1 failing
1) Ebay Smart Contract
"before each" hook for "if the base Price is less than 0 or invalid should revert":
Error: No Contract deployed with name Ebay
at Object.getContract (node_modules\#nomiclabs\hardhat-ethers\src\internal\helpers.ts:447:11)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at Context.<anonymous> (test\Test.js:18:12)
error Command failed with exit code 1.
MY TEST.js
//it
//describe
//beforeEach
const { expect, assert } = require("chai");
const { ethers, getNamedAccounts } = require("hardhat");
describe("Ebay Smart Contract", async function() {
let Ebay;
let deployer;
const product = {
name: "CYCLE",
description: "gare cycles",
BasePrice: "5",
};
beforeEach(async () => {
deployer = (await getNamedAccounts()).deployer;
console.log("This is deployer" + deployer);
Ebay = await ethers.getContract("Ebay", deployer);
});
describe("Upload Product function", async function() {
it("if the base Price is less than 0 or invalid should revert", async function() {
expect(
Ebay.UploadProduct(product.name, product.description, product.BasePrice)
).to.be.revertedWith(Base_Price_cannot_be_Zero());
});
});
});
My deploy.js
const { ethers, deployments } = require("hardhat");
require("dotenv").config();
async function main() {
// const { deploy, log } = deployments;
//const { deployer } = await getNamedAccounts();
const Auction = await ethers.getContractFactory("Ebay");
const auction = await Auction.deploy();
await auction.deployed();
console.log(auction.address);
// const Auction = await deploy("Auctionbargain", {
// from: deployer,
// args: [],
// log: true,
// waitconfirmations: network.config.blockConfirmations || 1,
// });
//console.log(Auction.address);
//log("------------------------------------");
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.log(error);
process.exit(1);
});
hardhatconfig.js
require("#nomicfoundation/hardhat-toolbox");
require("hardhat-deploy");
require("dotenv").config();
/** #type import('hardhat/config').HardhatUserConfig */
module.exports = {
solidity: {
compilers: [{ version: "0.6.6" }, { version: "0.8.8" }],
},
networks: {
hardhat: {
chainId: 31337,
},
// goerli: {
// url: GOERLI_RPC_URL,
// accounts: [PRIVATE_KEY],
// chainId: 5,
// blockConfirmations: 6,
// },
},
namedAccounts: {
deployer: {
default: 0, // here this will by default take the first account as deployer
},
},
};
It was correctly deployed but gave error everytime i try to test it
I Tried using ABI in place of deployer in my test.js but it did give me the same error
Are you sure you deployed the contract on the same network on which you’re testing? it says:
Error: No Contract deployed with name Ebay
this can happen if you‘re testing on another network where the contract isn’t deployed at.
Also consider that the contract is really named Ebay. I can’t check that since you didn’t provide the solidity file.
Related
I'm trying to automate a web activity using CodeceptJS (with Puppeteer) running in a Google Cloud Function.
My index.js is:
const Container = require('codeceptjs').container;
const Codecept = require('codeceptjs').codecept;
const event = require('codeceptjs').event;
const path = require('path');
module.exports.basicTest = async (req, res) => {
let message = '';
// helpers config
let config = {
tests: './*_test.js',
output: './output',
helpers: {
Puppeteer: {
url: 'https://github.com', // base url
show: true,
disableScreenshots: true, // don't store screenshots on failure
windowSize: '1200x1000', // set window size dimensions
waitForAction: 1000, // increase timeout for clicking
waitForNavigation: [ 'domcontentloaded', 'networkidle0' ], // wait for document to load
chrome: {
args: ['--no-sandbox'] // IMPORTANT! Browser can't be run without this!
}
}
},
include: {
I: './steps_file.js'
},
bootstrap: null,
mocha: {},
name: 'basic_test',
// Once a tests are finished - send back result via HTTP
teardown: (done) => {
res.send(`Finished\n${message}`);
}
};
// pass more verbose output
let opts = {
debug: true,
steps: true
};
// a simple reporter, let's collect all passed and failed tests
event.dispatcher.on(event.test.passed, (test) => {
message += `- Test "${test.title}" passed 😎`;
});
event.dispatcher.on(event.test.failed, (test) => {
message += `- Test "${test.title}" failed 😭`;
});
// create runner
let codecept = new Codecept(config, opts);
// codecept.init(testRoot)
codecept.initGlobals(__dirname);
// create helpers, support files, mocha
Container.create(config, opts);
try {
// initialize listeners
codecept.bootstrap();
// load tests
codecept.loadTests('*_test.js');
// run tests
codecept.run();
} catch (err) {
printError(err)
process.exitCode = 1
} finally {
await codecept.teardown()
}
}
and my simple test is:
Feature('Basic Automation');
Scenario('Basic Test', async ({ I }) => {
// ===== Login =====
pause()
I.amOnPage('https://cotps.com');
I.see('Built for developers', 'h1');
});
If I run it using npx codeceptjs run --steps it works but if I run it using node -e 'require("./index").basicTest() I get the error:
Cannot read property 'goto' of undefined. I also get the error if I deploy it to GCP and run it. I've looked through the docs for both Codecept and Puppeteer but found nothing and the only examples online are for previous versions of the libraries.
I'm trying to setup the plaid api in my node.js code and I need to be able to make a request for the create_link_token. The sample code from their docs is as follows:
const request: LinkTokenCreateRequest = {
user: {
client_user_id: 'user-id',
},
client_name: 'Plaid Test App',
products: ['auth', 'transactions'],
country_codes: ['US'],
language: 'en',
webhook: 'https://sample-web-hook.com',
redirect_uri: 'https://domainname.com/oauth-page.html',
account_filters: {
depository: {
account_subtypes: ['DepositoryAccountSubtype.Checking, DepositoryAccountSubtype.Savings'],
},
},
};
try {
const response = await plaidClient.linkTokenCreate(request);
const linkToken = response.data.link_token;
} catch (error) {
// handle error
}
my code is:
app.post('/api/create_link_token', async (req, res, next) => {
const request: LinkTokenCreateRequest = {
user: {
client_user_id: 'user-id',
},
client_name: 'Plaid Test App',
products: ['auth', 'transactions'],
country_codes: ['US'],
language: 'en',
webhook: 'https://sample-web-hook.com',
redirect_uri: 'https://domainname.com/oauth-page.html',
account_filters: {
depository: {
account_subtypes: ['DepositoryAccountSubtype.Checking, DepositoryAccountSubtype.Savings'],
},
},
};
try {
const response = await plaidClient.linkTokenCreate(request);
const linkToken = response.data.link_token;
} catch(e) {
handleError(e);
}
});
Right off the bat I get the error: 'LinkTokenCreateRequest' refers to a value, but is being used as a type here. Did you mean 'typeof LinkTokenCreateRequest'?ts(2749) as a red underline underneath LinkTokenCreateRequest. Side note I've never used TS before this, but I believe I have to use it on this project because some of their components require it. If I do as they suggest and change it to typeof LinkTokenCreateRequest = {... then the red underline error goes away, however upon starting the server I get the error:
const request: typeof LinkTokenCreateRequest = {
^^^^^^^
SyntaxError: Missing initializer in const declaration
I've very confused as to how I can make this work so any suggestions would be much appreciated.
I successfully installed and loaded kuzzle-device-manager in the backend file:
import { Backend } from 'kuzzle';
import { DeviceManagerPlugin } from 'kuzzle-device-manager';
const app = new Backend('playground');
console.log(app.config);
const deviceManager = new DeviceManagerPlugin();
const mappings = {
updatedAt: { type: 'date' },
payloadUuid: { type: 'keyword' },
value: { type: 'float' }
}
deviceManager.devices.registerMeasure('humidity', mappings)
app.plugin.use(deviceManager)
app.start()
.then(async () => {
// Interact with Kuzzle API to create a new index if it does not already exist
console.log(' started!');
})
.catch(console.error);
But when i try to use controllers from that plugin for example device-manager/device with create action i get an error output.
Here is my "client" code in js:
const { Kuzzle, WebSocket } = require("kuzzle-sdk")
const kuzzle = new Kuzzle(
new WebSocket('KUZZLE_IP')
)
kuzzle.on('networkError', error => {
console.error('Network Error: ', error);
})
const run = async () => {
try {
// Connects to the Kuzzle server
await kuzzle.connect();
// Creates an index
const result = await kuzzle.query({
index: "nyc-open-data",
controller: "device-manager/device",
action: "create",
body: {
model: "model-1234",
reference: "reference-1234"
}
}, {
queuable: false
})
console.log(result)
} catch (error) {
console.error(error.message);
} finally {
kuzzle.disconnect();
}
};
run();
And the result log:
API action "device-manager/device":"create" not found
Note: The nyc-open-data index exists and is empty.
We apologize for this mistake in the documentation, the device-manager/device:create method is not available because the plugin is using auto-provisioning until the v2.
You should send a payload to your decoder, the plugin will automatically provision the device if it does not exists https://docs.kuzzle.io/official-plugins/device-manager/1/guides/decoders/#receive-payloads
We had a test running successfully for our code that uses the notifications-node-client to send emails, eg
import { NotifyClient } from 'notifications-node-client';
import notify from './notify';
import config from '../../../config';
jest.mock('fs');
jest.mock('notifications-node-client');
describe('notify', () => {
const EMAIL = 'user#test.com';
const REGION_GB = 'gb';
const REGION_NI = 'ni';
const feedbackOptions = {
personalisation: {
satisfactionLevel: 'satisfied',
improvements: 'improvements',
},
};
test('for original GB submission sendEmail should be called and true returned', async () => {
NotifyClient.prototype.sendEmail.mockReturnValue({
body: {
id: 1,
},
});
expect(await notify(EMAIL, 'submissionSuccess', REGION_GB)).toBeTruthy();
expect(NotifyClient.prototype.sendEmail).toHaveBeenCalledWith(
config.notify.templates.submissionSuccess.gb,
EMAIL,
undefined,
);
});
...
Having swapped out our Winston logging solution to use #dwp/node-logger, the 'notify' tests now do not run, failing with
● Test suite failed to run
AssertionError [ERR_ASSERTION]: opts.entryPoint required
at new Thrift (node_modules/thriftrw/thrift.js:64:5)
at Object.<anonymous> (node_modules/jaeger-client/src/thrift.js:21:20)
at Object.<anonymous> (node_modules/jaeger-client/src/reporters/remote_reporter.js:15:1)
All of the other test suites in the project still run successfully.
Could anyone point me in the right direction about what change to make?
The code that we're testing is
import { NotifyClient } from 'notifications-node-client';
import config from '../../../config/index';
import { RegionKeys } from '../../../config/types';
import logger from '../../../xxxx/lib/logger';
type TemplateId = 'submissionSuccess' | 'supportingEvidence' | 'feedbackTemplateId';
type FeedbackOptions = {
personalisation: {
satisfactionLevel: string,
improvements: string,
},
reference?: string,
}
const { apiKey, templates, proxy } = config.notify;
export default async function notify(
email: string,
templateId: TemplateId,
region: RegionKeys,
options?: FeedbackOptions,
): Promise<boolean> {
let notifyTemplate;
let notifyApiKey;
let notifyOptions;
try {
if (templateId === 'feedbackTemplateId' && !options) {
throw new Error(`Unable to send email - mismatch between template ID (${templateId}) and options supplied`);
} else if (options && templateId !== 'feedbackTemplateId') {
notifyOptions = {};
} else {
notifyOptions = options;
}
const notifyClient = new NotifyClient(apiKey[region]);
notifyClient.setProxy(proxy);
notifyTemplate = templateId === 'feedbackTemplateId' ? templates.feedbackTemplateId : templates[templateId][region];
logger.debug(`apiKey: ${notifyApiKey}`);
logger.debug(`notify template Id: ${notifyTemplate}`);
logger.debug(`proxy: ${JSON.stringify(proxy)}`);
const response = await notifyClient.sendEmail(notifyTemplate, email, notifyOptions);
if (response.body) {
logger.info(`confirmation email sent to ${email} and relates to message id ${response.body.id}`);
}
return true;
} catch (err: any) {
logger.error(`there was an error sending the message: ${err.message}`);
return false;
}
}
I am using protractor having Jasmine where I intergrated stackdriver lib #google-cloud/logging. When I run this lib, I get entryId however I dont see logs in stackdriver. I debug the issues and seems like some issues with async-await concepts:
jasmine.getEnv().addReporter({
specDone: function (result) {
if(result.failedExpectations.length){
count++;
}
},
suiteDone: function (result) {
console.log(count);
if (count!=0) {
(async() => {
console.log('1')
await stackdriverLogEntry("Your GCP project", "protractor-log-data", "success: false");
console.log('2')
})()
} else {
(async() => {
console.log('3')
await stackdriverLogEntry("Your GCP project", "protractor-log-data", "success: true");
console.log('4')
})()
};
}
})
---------------------------------------------------------------------------
this.stackdriverLogEntry = async function (projectId, logName, text) {
// Creates a client
const logging = new Logging({ projectId: projectId });
// Selects the log to write to
const log = logging.log(logName);
// The metadata associated with the entry
const metadata = {
resource: { type: 'global' },
};
// Prepares a log entry
const entry = log.entry(metadata, text);
console.log(JSON.stringify(entry));
// Writes the log entry
await log.write(entry);
console.log(`metadata: ${JSON.stringify(metadata)}`);
console.log(`Logged: ${text}`);
};
Any HELP here would be appreciated!!!