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

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'));
});

Related

before, beforeEach does not execute in hardhat test

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.

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);
})

How do get value from async function without then()

I know I have to use then() or in a async function to use await to get the value from other async function .
but how to I get value directly ?
I try to pass the value in normal function but not work .
there is no other way to get the value directly ?
thanks
here is ample :
load_data_normal(key){
this.load_data(key).then((ret_val)=>{
console.log(ret_val);
return ret_val;
})
}
load_data = async (key) => {
const MMM = await AsyncStorage.getItem(key);
return MMM;
}
load_data function just work with then(), but load_data_normal not work ,
I just want to get value from get_data without then ..
The simple solution is just adding async to your load_data_normal, if you want to know more read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
load_data_normal = async (key) => {
const ret_val = await this.load_data(key);
return ret_val;
}
load_data = async (key) => {
const MMM = await AsyncStorage.getItem(key);
return MMM;
}
Normal function doesn't work with await. You need an async function.
const asynFunction = async() => {
const results = await fetch(url);
console.log('results', results)
}
If you don't want to use async, you need to create a new promise.
const load_data_normal = (key) => {
localStorage.setItem("abc", "somevalue in abc");
load_data(key).then((resuls) => {
console.log("abc", resuls);
});
};
const load_data = (someKey) => {
return new Promise((resolve) => resolve(localStorage.getItem(someKey)));
};
load_data_normal("abc");
Sandbox

Reusing async function in react native

I am building a page to fetch data from API when loaded, but encounter waring an effect function must not return anything besides a function which is used for clean-up when trying to reuse the function for fetching data
const dispatch = useDispatch();
useEffect(() => {
// this way does not work as I expected, my page does not show data I fetched
const getData = async () => {
const result = await dispatch(actions.getList());
setState(result);
};
getData();
},[isFirstLoaded]);
But I get the warning when trying below
const dispatch = useDispatch();
const getData = async () => {
const result = await dispatch(actions.getList());
setState(result);
};
useEffect(async() => {
// this way gives me the data but with a warning
await getData();
},[isFirstLoaded]);
How should I reuse the getData function? I did not update the state if I am not using the async and await here. When I use async and await here, I get the warning. Thanks.
overall, you are heading in the right direction. For fetching data, you'd wanna use use Effect and pass [] as a second argument to make sure it fires only on initial mount.
I believe you could benefit from decoupling fetching function and making it more generic, as such:
const fetchJson = async (url) => {
const response = await fetch(url);
return response.json();
};
const Fetch = () => {
const [data, setData] = useState(null);
useEffect(() => {
fetchJson("https://api.coindesk.com/v1/bpi/currentprice.json")
.then(({ disclaimer }) => setData(disclaimer));
}, []);
return <Text>{data}</Text>;
};

Calling async function from custom flatlist view

I am trying to call an async function in a customer flatlist view, but I am get errors caused by using await in the custom flatlist view:
async _customFlatlistView(item){
promise = await SomeFunction();
promise2 = await SomeOtherFunction();
}
await can only be used in async functions
_customFlatlistView = async item => {
promise = await SomeFunction()
promise2 = await SomeOtherFunction()
}
The await keyword can only be used in adding the async keyword to the method signature:
async _customFlatlistView(item){
promise = await SomeFunction();
promise2 = await SomeOtherFunction();
}