before, beforeEach does not execute in hardhat test - testing

This code is for testing a Silent Auction smart contract written in hardhat.
When I type everything separately into the it{...} blocks, the test are passing. When using before, and beforeEach to simplify the code it doesnt work.
Error message: "ReferenceError: silentAuction is not defined"
Can somebody tell me which part I do wrong?
const { BigNumber } = require("ethers");
const { ethers } = require("hardhat");
describe("SilentAuction", function () {
before(async function () {
const SilentAuction = await ethers.getContractFactory("SilentAuction");
})
beforeEach(async function () {
const silentAuction = await SilentAuction.deploy();
await silentAuction.deployed();
})
describe("- setItem function tests", function (){
it("Owner should be able to set an item for bid", async function () {
//const SilentAuction = await ethers.getContractFactory("SilentAuction");
//const silentAuction = await SilentAuction.deploy();
//await silentAuction.deployed();
await silentAuction.setItem("SAMPLE", 100, 300);
expect((await silentAuction.items(0)).name).to.be.equal("SAMPLE");
expect((await silentAuction.items(0)).highestPrice.toString()).to.be.equal('100');
expect((await silentAuction.items(0)).successLimit.toString()).to.be.equal('300');
});
it("Not owner cannot call function", async function () {
const [owner, addr1] = await ethers.getSigners();
//const SilentAuction = await ethers.getContractFactory("SilentAuction");
//const silentAuction = await SilentAuction.deploy();
//await silentAuction.deployed();
await expect(silentAuction.connect(addr1).setItem("SAMPLE", 100, 300)).to.be.reverted;
});
});
describe("- bid function tests", function (){
it("Everyone should place a bid", async function () {
const [owner, addr1] = await ethers.getSigners();
//const SilentAuction = await ethers.getContractFactory("SilentAuction");
//const silentAuction = await SilentAuction.deploy();
//await silentAuction.deployed();
await silentAuction.connect(owner).setItem("SAMPLE", 100, 300);
await silentAuction.connect(addr1).bid(200);
expect((await silentAuction.items(0)).highestPrice.toString()).to.be.equal('200');
})
it("Should not replace smaller bids than the recent highest", async function () {
const [owner, addr1] = await ethers.getSigners();
//const SilentAuction = await ethers.getContractFactory("SilentAuction");
//const silentAuction = await SilentAuction.deploy();
//await silentAuction.deployed();
await silentAuction.connect(owner).setItem("SAMPLE", 100, 300);
await silentAuction.connect(addr1).bid(50);
expect((await silentAuction.items(0)).highestPrice.toString()).to.be.equal('100');
})
})
});

silentAuction is a constant which is defined in the scope of before or beforeEach function, not in the scope of whole tests.
If you want to use such variable in the whole tests, you should do something like this:
describe('foo' () => {
let silentAuction;
beforeEach(() => {
silentAuction = ...
})
})
Also the reason you get reference error is that every test function can't find such variable within its or outer scope then it raises Reference Error.

Related

Mock, jest and time

I read some tips on how to mock your request/response in Express framework in the blog:
https://codewithhugo.com/express-request-response-mocking/. However, I have no clue how to mock the controller below.
export const healthCheck = async (req, res, next) => {
log("debug", "healthCheck controller called");
const healthcheck = {
uptime: process.uptime(),
message: "Server is running!",
now_timestamp: Date.now()
};
try {
res.send(healthcheck);
} catch (error) {
healthcheck.message = error;
res.status(503).send();
}
};
I am glad to share my efforts below. My suspicion is that I must mock class Date as well.
import {
healthCheck
} from "../healthcheck.js";
const mockRequest = () => {
const req = {}
req.body = jest.fn().mockReturnValue(req)
req.params = jest.fn().mockReturnValue(req)
return req
};
const mockResponse = () => {
const res = {}
res.get = jest.fn().mockReturnValue(res)
res.send = jest.fn().mockReturnValue(res)
res.status = jest.fn().mockReturnValue(res)
res.json = jest.fn().mockReturnValue(res)
return res
};
const mockNext = () => {
return jest.fn()
};
describe("healthcheck", () => {
afterEach(() => {
// restore the spy created with spyOn
jest.restoreAllMocks();
});
it("should call mocked log for invalid from scaler", async () => {
let req = mockRequest();
let res = mockResponse();
let next = mockNext();
await healthCheck(req, res, next);
expect(res.send).toHaveBeenCalledTimes(1)
expect(res.send.mock.calls.length).toBe(1);
});
});

npx hardhat test returns "0 passing" no matter what I try

I am following this tutorial on youtube "https://www.youtube.com/watch?v=7QsqElEaWBQ"
And I have double checked to make sure my code matches, but I am stuck at the 41:00 minute mark where I am testing the project. It consistently shows "0 passing". There is no fail message which I saw in the tutorial video. This makes me believe that they aren't even getting tested. I have installed all dependencies required in the beginning, checked to make sure my file names match and still no luck. This test is using using hardhat-waffle.
Here is my "Testing.js" file code =>
const { expect } = require("chai");
const { ethers } = require("ethers");
const {
isCallTrace,
} = require("hardhat/internal/hardhat-network/stack-traces/message-trace");
describe("Staking", function () {
beforeEach(async function () {
[signer1, signers2] = await ethers.getSigners();
Staking = await ethers.getContractFactory("Staking", signer1);
staking = await Staking.deploy({
value: ethers.utils.parseEther("10"),
});
});
describe("deploy", function () {
it("should set owner", async function () {
expect(await staking.owner()).to.equal(signer1.address);
});
it("sets up tiers and lockPeriods", async function () {
expect(await staking.lockPeriods(0)).to.equal(30);
expect(await staking.lockPeriods(1)).to.equal(90);
expect(await staking.lockPeriods(2)).to.equal(180);
expect(await staking.tiers(3)).to.equal(700);
expect(await staking.tiers(3)).to.equal(1000);
expect(await staking.tiers(3)).to.equal(1200);
});
});
describe("stakeEther", function () {
it("transfers ether", async function () {
const provider = waffle.provider;
let contractBalance;
let signerBalance;
const transferAmount = ethers.utils.parseEther("2.0");
contractBalance = await provider.getBalance(staking.address);
signerBalance = await signer1.getBalance();
const data = { value: transferAmount };
const transaction = await staking.connect(signer1).stakeEther(30, data);
const receipt = await transaction.wait();
const gasUsed = receipt.gasUsed.mul(receipt.effectiveGasPrice);
//test the change in signer1's ether balance
expect(await signer1.getBalance()).to.equal(
signerBalance.sub(transferAmount).sub(gasUsed)
);
// test the change in contract's ether balance
expect(await provider.getBalance(staking.address)).to.equal(
contractBalance.add(transferAmount)
);
});
});
});
If you know how to solve my issue, please let me know. That would be a great help to me!
Please be sure, that Testing.js is placed in the folder test and folder test is placed next to package.json

A call to an async function is not awaited. Use the "await" keyword in Test Cafe

I'm getting this error:
A call to an async function is not awaited. Use the "await" keyword
before actions, assertions or chains of them to ensure that they run
in the right sequence.
But I am using an await within my code, what am I doing incorrectly?
test("Accepts the cookie", async t => {
const interfaceSelect = Selector('#sp_message_iframe_617100');
await
t.switchToIframe('#sp_message_iframe_617100')
t.click(Selector('button').withText('Accept'))
t.switchToIframe('#select_region-select-module_select_30IZf')
const countrySelect = Selector('#region-select-module_select__30lZf');
t.click(Selector('button').withText('United Kingdom'))
});
Thanks,
The TestCafe's methods are chainable and return a Promise.
You need to add an await before each method call or one await before the whole chain.
test("Accepts the cookie", async t => {
const interfaceSelect = Selector('#sp_message_iframe_617100');
await t.switchToIframe('#sp_message_iframe_617100');
await t.click(Selector('button').withText('Accept'));
await t.switchToIframe('#select_region-select-module_select_30IZf');
const countrySelect = Selector('#region-select-module_select__30lZf');
await t.click(Selector('button').withText('United Kingdom'));
});
test("Accepts the cookie", async t => {
const interfaceSelect = Selector('#sp_message_iframe_617100');
await t
.switchToIframe('#sp_message_iframe_617100')
.click(Selector('button').withText('Accept'))
.switchToIframe('#select_region-select-module_select_30IZf');
const countrySelect = Selector('#region-select-module_select__30lZf');
await t.click(Selector('button').withText('United Kingdom'));
});

Jest does not continue after async method

I have an async method triggered by a click event where I make a call to an API and then process the response, like this:
async confirmName () {
const {name, description} = this.form;
const [data, error] = await Pipelines.createPipeline({name, description});
if (error) {
console.error(error);
this.serviceError = true;
return false;
}
this.idPipelineCreated = data.pipeline_id;
return true;
}
The test looks like this:
test("API success", async () => {
const ConfirmNameBtn = wrapper.find(".form__submit-name");
await ConfirmNameBtn.vm.$emit("click");
const pipelinesApi = new Pipelines();
jest.spyOn(pipelinesApi, "createPipeline").mockResolvedValue({pipeline_id: 100});
const {name, description} = wrapper.vm.form;
pipelinesApi.createPipeline().then(data => {
expect(wrapper.vm.pipelineNameServiceError).toBe(false);
wrapper.setData({
idPipelineCreated: data.pipeline_id
});
expect(wrapper.vm.idPipelineCreated).toBe(data.pipeline_id)
}).catch(() => {})
})
A basic class mock:
export default class Pipelines {
constructor () {}
createPipeline () {}
}
I'm testing a success API call and I mock the API call returning a resolved promised. The problem is the coverage only covers the first two lines of the method, not the part where I assign the response of the API call. Is this the correct approach?
Edit:
Screenshot of coverage report:
Don't mix up await and then/catch. Prefer using await unless you have very special cases (see this answer):
test("API success", async () => {
const ConfirmNameBtn = wrapper.find(".form__submit-name");
await ConfirmNameBtn.vm.$emit("click");
const pipelinesApi = new Pipelines();
jest.spyOn(pipelinesApi, "createPipeline").mockResolvedValue({pipeline_id: 100});
const {name, description} = wrapper.vm.form;
const data = await pipelinesApi.createPipeline();
expect(wrapper.vm.pipelineNameServiceError).toBe(false);
wrapper.setData({
idPipelineCreated: data.pipeline_id
});
expect(wrapper.vm.idPipelineCreated).toBe(data.pipeline_id)
expect(wrapper.vm.serviceError).toBe(false);
})

Where is module './get-username'?

I am attempting to write a script using the puppeteer library for node and I'm running it on the microtask platform rapidworkers.com
I have run into a challenge when writing part of the script that solves the captcha on the rapidworkers login page, when I try to run my script with node index.js I get the error: Cannot find module './get-username'
here is my code: (copied from https://jsoverson.medium.com/bypassing-captchas-with-headless-chrome-93f294518337)
const puppeteer = require('puppeteer');
const request = require('request-promise-native');
const poll = require('promise-poller').default;
const siteDetails = {
sitekey: '6LeEP20UAAAAAPYQsP7kIhE7XUT_LsDYjzO46uG3',
pageurl: 'https://rapidworkers.com/Login'
}
const getUsername = require('./get-username');
const getPassword = require('./get-password');
const apiKey = require('./api-key');
const chromeOptions = {
executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google
Chrome',
headless:false,
slowMo:10,
defaultViewport: null
};
(async function main() {
const browser = await puppeteer.launch(chromeOptions);
const page = await browser.newPage();
await page.goto('https://rapidworkers.com/Login');
const requestId = await initiateCaptchaRequest(apiKey);
await page.type('#username', getUsername());
const password = getPassword();
await page.type('#password', password);
const response = await pollForRequestResults(apiKey, requestId);
await page.evaluate(`document.getElementById("g-recaptcha-
response").innerHTML="${response}";`);
page.click('#register-form button[type=submit]');
})()
async function initiateCaptchaRequest(apiKey) {
const formData = {
method: 'userrecaptcha',
googlekey: siteDetails.sitekey,
key: apiKey,
pageurl: siteDetails.pageurl,
json: 1
};
const response = await request.post('http://2captcha.com/in.php', {form:
formData});
return JSON.parse(response).request;
}
async function pollForRequestResults(key, id, retries = 30, interval = 1500,
delay = 15000) {
await timeout(delay);
return poll({
taskFn: requestCaptchaResults(key, id),
interval,
retries
});
}
function requestCaptchaResults(apiKey, requestId) {
const url = `http://2captcha.com/res.php?
key=${apiKey}&action=get&id=${requestId}&json=1`;
return async function() {
return new Promise(async function(resolve, reject){
const rawResponse = await request.get(url);
const resp = JSON.parse(rawResponse);
if (resp.status === 0) return reject(resp.request);
resolve(resp.request);
});
}
}
const timeout = millis => new Promise(resolve => setTimeout(resolve,
millis))