Test an Async function in JS - Error: “Did you forget to use await”
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
My code looks like this:
public getUrl(url) {
//returns URL
... }
public getResponseFromURL(): container {
let myStatus = 4;
const abc = http.get(url, (respon) =>
const { statusCode } = respon;
myStatus = statusCode;
console.log('Inside callback' +myStatus);
.on('error', (err) => {
console.log('Things have gone wrong' + err);
});
console.log('ITS COMPLICATED' +myStatus);
return new Container(status, body, header);
}
}
The problem I am facing is because of the asynchronous nature of JS and the console.log('ITS COMPLICATED') gets executed before the one in the callback function. I am trying to have the first one executed before the last console.log!
I am using Async/Await like below:
public timeoutPromise(time: any) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Date.now());
}, time);
});
}
public doSomethingAsync() {
return this.timeoutPromise(1000);
}
As a result changed my getResponseFromURL() to:
public async getResponseFromURL(): Promise<container> {
this.myStatus = 7;
console.log(0);
await this.doSomethingAsync();
console.log(1);
const abc = http.get(url, (respon) => {
const { statusCode } = respon;
this.myStatus = statusCode;
console.log('Inside Callback ' + statusCode);
}).on('error', (err) => {
console.log('Things have gone wrong ' + err);
});
await this.doSomethingAsync();
console.log(2);
await this.doSomethingAsync();
console.log('Is it simple lalala ' + this.myStatus);
await this.doSomethingAsync();
}
}
The problem with doing this was if my container class (return type of getResponseFromURL()) is a container for status and body when I am testing this async function, before expect.getResponseFromURL().getStatus().toBe(200)
would work.
Test looks like below:
test('Async function', async () => {
expect.assertions(1);
const data = await ContainerGlobals.getResponseFromURL().getStatus();
expect(data).toBe(207);
});
Now I am getting error from .getStatus()
and I am not sure how to bypass this error?
"does not exist on Promise"
typescript async-await jestjs es6-promise
add a comment |
My code looks like this:
public getUrl(url) {
//returns URL
... }
public getResponseFromURL(): container {
let myStatus = 4;
const abc = http.get(url, (respon) =>
const { statusCode } = respon;
myStatus = statusCode;
console.log('Inside callback' +myStatus);
.on('error', (err) => {
console.log('Things have gone wrong' + err);
});
console.log('ITS COMPLICATED' +myStatus);
return new Container(status, body, header);
}
}
The problem I am facing is because of the asynchronous nature of JS and the console.log('ITS COMPLICATED') gets executed before the one in the callback function. I am trying to have the first one executed before the last console.log!
I am using Async/Await like below:
public timeoutPromise(time: any) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Date.now());
}, time);
});
}
public doSomethingAsync() {
return this.timeoutPromise(1000);
}
As a result changed my getResponseFromURL() to:
public async getResponseFromURL(): Promise<container> {
this.myStatus = 7;
console.log(0);
await this.doSomethingAsync();
console.log(1);
const abc = http.get(url, (respon) => {
const { statusCode } = respon;
this.myStatus = statusCode;
console.log('Inside Callback ' + statusCode);
}).on('error', (err) => {
console.log('Things have gone wrong ' + err);
});
await this.doSomethingAsync();
console.log(2);
await this.doSomethingAsync();
console.log('Is it simple lalala ' + this.myStatus);
await this.doSomethingAsync();
}
}
The problem with doing this was if my container class (return type of getResponseFromURL()) is a container for status and body when I am testing this async function, before expect.getResponseFromURL().getStatus().toBe(200)
would work.
Test looks like below:
test('Async function', async () => {
expect.assertions(1);
const data = await ContainerGlobals.getResponseFromURL().getStatus();
expect(data).toBe(207);
});
Now I am getting error from .getStatus()
and I am not sure how to bypass this error?
"does not exist on Promise"
typescript async-await jestjs es6-promise
You could try something like this async doSomethingAsync() { this.asyncResult = await this.httpClient.get(this.url).toPromise(); console.log('No issues, I will wait until promise is resolved..'); }
– Anoop Mc
Jan 4 at 17:14
@AnoopMc I am not sure I understand - what is this.httpClient and toPromise() here ?
– lanzchilz
Jan 4 at 17:45
add a comment |
My code looks like this:
public getUrl(url) {
//returns URL
... }
public getResponseFromURL(): container {
let myStatus = 4;
const abc = http.get(url, (respon) =>
const { statusCode } = respon;
myStatus = statusCode;
console.log('Inside callback' +myStatus);
.on('error', (err) => {
console.log('Things have gone wrong' + err);
});
console.log('ITS COMPLICATED' +myStatus);
return new Container(status, body, header);
}
}
The problem I am facing is because of the asynchronous nature of JS and the console.log('ITS COMPLICATED') gets executed before the one in the callback function. I am trying to have the first one executed before the last console.log!
I am using Async/Await like below:
public timeoutPromise(time: any) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Date.now());
}, time);
});
}
public doSomethingAsync() {
return this.timeoutPromise(1000);
}
As a result changed my getResponseFromURL() to:
public async getResponseFromURL(): Promise<container> {
this.myStatus = 7;
console.log(0);
await this.doSomethingAsync();
console.log(1);
const abc = http.get(url, (respon) => {
const { statusCode } = respon;
this.myStatus = statusCode;
console.log('Inside Callback ' + statusCode);
}).on('error', (err) => {
console.log('Things have gone wrong ' + err);
});
await this.doSomethingAsync();
console.log(2);
await this.doSomethingAsync();
console.log('Is it simple lalala ' + this.myStatus);
await this.doSomethingAsync();
}
}
The problem with doing this was if my container class (return type of getResponseFromURL()) is a container for status and body when I am testing this async function, before expect.getResponseFromURL().getStatus().toBe(200)
would work.
Test looks like below:
test('Async function', async () => {
expect.assertions(1);
const data = await ContainerGlobals.getResponseFromURL().getStatus();
expect(data).toBe(207);
});
Now I am getting error from .getStatus()
and I am not sure how to bypass this error?
"does not exist on Promise"
typescript async-await jestjs es6-promise
My code looks like this:
public getUrl(url) {
//returns URL
... }
public getResponseFromURL(): container {
let myStatus = 4;
const abc = http.get(url, (respon) =>
const { statusCode } = respon;
myStatus = statusCode;
console.log('Inside callback' +myStatus);
.on('error', (err) => {
console.log('Things have gone wrong' + err);
});
console.log('ITS COMPLICATED' +myStatus);
return new Container(status, body, header);
}
}
The problem I am facing is because of the asynchronous nature of JS and the console.log('ITS COMPLICATED') gets executed before the one in the callback function. I am trying to have the first one executed before the last console.log!
I am using Async/Await like below:
public timeoutPromise(time: any) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Date.now());
}, time);
});
}
public doSomethingAsync() {
return this.timeoutPromise(1000);
}
As a result changed my getResponseFromURL() to:
public async getResponseFromURL(): Promise<container> {
this.myStatus = 7;
console.log(0);
await this.doSomethingAsync();
console.log(1);
const abc = http.get(url, (respon) => {
const { statusCode } = respon;
this.myStatus = statusCode;
console.log('Inside Callback ' + statusCode);
}).on('error', (err) => {
console.log('Things have gone wrong ' + err);
});
await this.doSomethingAsync();
console.log(2);
await this.doSomethingAsync();
console.log('Is it simple lalala ' + this.myStatus);
await this.doSomethingAsync();
}
}
The problem with doing this was if my container class (return type of getResponseFromURL()) is a container for status and body when I am testing this async function, before expect.getResponseFromURL().getStatus().toBe(200)
would work.
Test looks like below:
test('Async function', async () => {
expect.assertions(1);
const data = await ContainerGlobals.getResponseFromURL().getStatus();
expect(data).toBe(207);
});
Now I am getting error from .getStatus()
and I am not sure how to bypass this error?
"does not exist on Promise"
typescript async-await jestjs es6-promise
typescript async-await jestjs es6-promise
edited Jan 10 at 16:26
skyboyer
4,33811333
4,33811333
asked Jan 4 at 17:07
lanzchilzlanzchilz
164
164
You could try something like this async doSomethingAsync() { this.asyncResult = await this.httpClient.get(this.url).toPromise(); console.log('No issues, I will wait until promise is resolved..'); }
– Anoop Mc
Jan 4 at 17:14
@AnoopMc I am not sure I understand - what is this.httpClient and toPromise() here ?
– lanzchilz
Jan 4 at 17:45
add a comment |
You could try something like this async doSomethingAsync() { this.asyncResult = await this.httpClient.get(this.url).toPromise(); console.log('No issues, I will wait until promise is resolved..'); }
– Anoop Mc
Jan 4 at 17:14
@AnoopMc I am not sure I understand - what is this.httpClient and toPromise() here ?
– lanzchilz
Jan 4 at 17:45
You could try something like this async doSomethingAsync() { this.asyncResult = await this.httpClient.get(this.url).toPromise(); console.log('No issues, I will wait until promise is resolved..'); }
– Anoop Mc
Jan 4 at 17:14
You could try something like this async doSomethingAsync() { this.asyncResult = await this.httpClient.get(this.url).toPromise(); console.log('No issues, I will wait until promise is resolved..'); }
– Anoop Mc
Jan 4 at 17:14
@AnoopMc I am not sure I understand - what is this.httpClient and toPromise() here ?
– lanzchilz
Jan 4 at 17:45
@AnoopMc I am not sure I understand - what is this.httpClient and toPromise() here ?
– lanzchilz
Jan 4 at 17:45
add a comment |
1 Answer
1
active
oldest
votes
In the code above await
is called on the result of calling getStatus
on the result of calling ContainerGlobals.getResponseFromURL()
.
ContainerGlobals.getResponseFromURL()
returns a Promise
and immediately calling getStatus()
on the Promise
gives an error since getStatus
"does not exist on Promise
".
await
needs to be called on the Promise
returned by ContainerGlobals.getResponseFromURL()
, and getStatus
should be called on the result returned by await
.
The quickest way to fix this is to throw parenthesis around the await
:
test('Async function', async () => {
expect.assertions(1);
const data = (await ContainerGlobals.getResponseFromURL()).getStatus();
expect(data).toBe(207); // SUCCESS
});
...but you might want to split the await
line into two lines for readability:
test('Async function', async () => {
expect.assertions(1);
const result = await ContainerGlobals.getResponseFromURL(); // let the Promise resolve
const data = result.getStatus(); // call getStatus on the result
expect(data).toBe(207); // SUCCESS
});
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54043275%2ftest-an-async-function-in-js-error-did-you-forget-to-use-await%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
In the code above await
is called on the result of calling getStatus
on the result of calling ContainerGlobals.getResponseFromURL()
.
ContainerGlobals.getResponseFromURL()
returns a Promise
and immediately calling getStatus()
on the Promise
gives an error since getStatus
"does not exist on Promise
".
await
needs to be called on the Promise
returned by ContainerGlobals.getResponseFromURL()
, and getStatus
should be called on the result returned by await
.
The quickest way to fix this is to throw parenthesis around the await
:
test('Async function', async () => {
expect.assertions(1);
const data = (await ContainerGlobals.getResponseFromURL()).getStatus();
expect(data).toBe(207); // SUCCESS
});
...but you might want to split the await
line into two lines for readability:
test('Async function', async () => {
expect.assertions(1);
const result = await ContainerGlobals.getResponseFromURL(); // let the Promise resolve
const data = result.getStatus(); // call getStatus on the result
expect(data).toBe(207); // SUCCESS
});
add a comment |
In the code above await
is called on the result of calling getStatus
on the result of calling ContainerGlobals.getResponseFromURL()
.
ContainerGlobals.getResponseFromURL()
returns a Promise
and immediately calling getStatus()
on the Promise
gives an error since getStatus
"does not exist on Promise
".
await
needs to be called on the Promise
returned by ContainerGlobals.getResponseFromURL()
, and getStatus
should be called on the result returned by await
.
The quickest way to fix this is to throw parenthesis around the await
:
test('Async function', async () => {
expect.assertions(1);
const data = (await ContainerGlobals.getResponseFromURL()).getStatus();
expect(data).toBe(207); // SUCCESS
});
...but you might want to split the await
line into two lines for readability:
test('Async function', async () => {
expect.assertions(1);
const result = await ContainerGlobals.getResponseFromURL(); // let the Promise resolve
const data = result.getStatus(); // call getStatus on the result
expect(data).toBe(207); // SUCCESS
});
add a comment |
In the code above await
is called on the result of calling getStatus
on the result of calling ContainerGlobals.getResponseFromURL()
.
ContainerGlobals.getResponseFromURL()
returns a Promise
and immediately calling getStatus()
on the Promise
gives an error since getStatus
"does not exist on Promise
".
await
needs to be called on the Promise
returned by ContainerGlobals.getResponseFromURL()
, and getStatus
should be called on the result returned by await
.
The quickest way to fix this is to throw parenthesis around the await
:
test('Async function', async () => {
expect.assertions(1);
const data = (await ContainerGlobals.getResponseFromURL()).getStatus();
expect(data).toBe(207); // SUCCESS
});
...but you might want to split the await
line into two lines for readability:
test('Async function', async () => {
expect.assertions(1);
const result = await ContainerGlobals.getResponseFromURL(); // let the Promise resolve
const data = result.getStatus(); // call getStatus on the result
expect(data).toBe(207); // SUCCESS
});
In the code above await
is called on the result of calling getStatus
on the result of calling ContainerGlobals.getResponseFromURL()
.
ContainerGlobals.getResponseFromURL()
returns a Promise
and immediately calling getStatus()
on the Promise
gives an error since getStatus
"does not exist on Promise
".
await
needs to be called on the Promise
returned by ContainerGlobals.getResponseFromURL()
, and getStatus
should be called on the result returned by await
.
The quickest way to fix this is to throw parenthesis around the await
:
test('Async function', async () => {
expect.assertions(1);
const data = (await ContainerGlobals.getResponseFromURL()).getStatus();
expect(data).toBe(207); // SUCCESS
});
...but you might want to split the await
line into two lines for readability:
test('Async function', async () => {
expect.assertions(1);
const result = await ContainerGlobals.getResponseFromURL(); // let the Promise resolve
const data = result.getStatus(); // call getStatus on the result
expect(data).toBe(207); // SUCCESS
});
answered Jan 7 at 3:38
brian-lives-outdoorsbrian-lives-outdoors
11.7k1930
11.7k1930
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54043275%2ftest-an-async-function-in-js-error-did-you-forget-to-use-await%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You could try something like this async doSomethingAsync() { this.asyncResult = await this.httpClient.get(this.url).toPromise(); console.log('No issues, I will wait until promise is resolved..'); }
– Anoop Mc
Jan 4 at 17:14
@AnoopMc I am not sure I understand - what is this.httpClient and toPromise() here ?
– lanzchilz
Jan 4 at 17:45