Reputation: 5402
I've been writing some unit tests and I noticed that I can't seem to find a good way to test asynchronous functions. So I found nock. It seems cool, only if it worked. I'm clearly missing something...
import nock from 'nock';
import request from 'request';
const profile = {
name: 'John',
age: 25
};
const scope = nock('https://mydomainname.local')
.post('/api/send-profile', profile)
.reply(200, {status:200});
request('https://mydomainname.local/api/send-profile').on('response', function(request) {
console.log(typeof request.statusCode); // this never hits
expect(request.statusCode).to.equal.(200);
});
request
never happens, so how can I test if nock actually returned {status:200}
? I've also tried fetch
and regular http
calls. Which makes me think it's something with my nock code? Thank you for your help in advance!
Upvotes: 0
Views: 1623
Reputation: 16246
Nock does not return {status:200}
because it's intercepting POST
request, but the request
statement is sending GET
request.
It seems you want to intercept POST
request with specified profile
? The code would be:
var nock = require('nock');
var request = require('request');
const profile = {
name: 'John',
age: 25
};
const scope = nock('https://mydomainname.local')
.post('/api/send-profile', profile)
.reply(200, {status:200});
request.post('https://mydomainname.local/api/send-profile', {json: {name: 'John', age: 25}}).on('response', function(request) {
console.log(request.statusCode); // 200
});
Upvotes: 2