Why does sinon fakeserver not reply to request from Vue component - javascript

I am chasing a race condition since days now. I am really glad for any help. This is both a sinon fakeserver and a Vue.js related question.
Here is the setup of my little project:
The project is based on the awesome vue webpack template.
I have a rather elaborate vue component called DoogieTable that shows a table. It can load data from a remote REST endpoint. (using vue-resource)
I have a mocha test case for DoogieTable. The second test about loading remote data into the table is my problem.
The test mocks the xHhtmlRequest with sinon.fakeServer and responds with canned data.
This works as long as I set fakeServer.autoRespond = true; But according to the sinon doc, this is not suitable for production ready unit tests.
When/Where in the code of my test case do I have to call fakeServer.respond() ?
Things I already tried:
Calling it right after the the vue component DoogieTable became ready => that seems to be to early. At that point in time, the request to load data has not been send by the component. (I think. I am not quite sure)
Calling in a vm.$nextTick callback => same problem. No request yet.

Related

nextjs api not working when fetching through isomorphic-unfetch

Im not getting my data (notes) inside the props, it is giving undefined when im using console.log(notes).
My backend api is also in the same project in /pages/api/notes/index.js
The api which im calling is 'http://localhost:3000/api/notes'
Even my api is working fine when im testing it on postman. But on the frontend, data isnt available
Please checkout this issue.
I believe that you simply have a typo. Index.getinitialProps should be Index.getInitialProps. Note that the "i" in initial is capitalized.
Also as a tip, you don't explicitly need http://localhost:3000, if you just call it with /api/notes it will correctly resolve the request. That way when you deploy the app you don't have to go back and make a ton of changes for your data fetches.

how to stop calling more requests in vuejs

I have a little problem with my application in VUEJS.
I have an API build in DRF(Django Rest Framework), and application build in VUEJS, when I tested my API in postman working well because I just call one time and the response is one too.
When I tested in my app VUEJS, calling 3 times and more like this:
in first 3 rows calling almost correct, but my app in VUEJS calling many times like images.
my method is created like this:
created(){
// this.DoTransPenalties();
},
mounted(){
this.DoTransPenalties();
},
methods{
DoTransPenalties(){
console.log('transaction canceled ', this.transactioId);
}
}
the method 'DoTransPenalties' is on mounted, in other cases, I put the 'DoTransPenalties' in created, but the same thing always calling many times,
and you can see the error GET, the API get a URL incorrect because the stranges characters in the URL.
please help me, could you say me if is the problem with the configuration of web pack or I need to use vuex, because I used vuex but the same problem.
thanks for your attention.

Why do I get "Ajax authorization fails" in my tests

I am following the ember tutorials, and specifically I'm on services.
I am 99.9% certain that I have the exact code in place -- I am copying by hand, because I believe that helps me absorb it more completely, but if anything fails I start using a diff checker to see if I made a typo. To my knowledge, no typos.
The App I have written performs identically to the screen shots in the tutorials, and the only error I get is a lint error for having a test that doesn't have an assert in it (yet).
Prior to this unit, all other tests have passed as well. But now I am getting failed tests that previously passed. They appear to all stem from the stubbed call to the map service failing. The first test that fails is integration/component/rental-listing-test.js:
hooks.beforeEach(function() {
this.rental = {
image: 'fake.png',
title: 'test-title',
owner: 'test-owner',
type: 'test-type',
city: 'test-city',
bedrooms: 3
};
});
test('should display rental details', async function(assert) {
await render(hbs`{{rental-listing rental=rental}}`);
assert.equal(this.element.querySelector('.listing h3').textContent.trim(), 'test-title', 'Title: test-title');
assert.equal(this.element.querySelector('.listing .owner').textContent.trim(), 'Owner: test-owner', 'Owner: test-owner');
});
If I remove the new line from rental-listing.hbs ( {{location-map location=rental.city}} ), thus preventing the map from being used, these tests once again pass (though the new tests for the component using the service have issues).
So either I am doing something wrong that I can't find, or else the fine folk at emberjs.com have not provided complete information in this tutorial. Do I need to somehow stub the map service? that appears in the .hbs file for the above test to pass? If so, why do you think they failed to mention this?
ETA assertion:
Ajax authorization failed # 273 ms
Source: Error: Ajax authorization failed
at new EmberError (http://localhost:7357/assets/vendor.js:13635:31)
at new AjaxError (http://localhost:7357/assets/vendor.js:116954:13)
at new UnauthorizedError (http://localhost:7357/assets/vendor.js:116968:13)
at Class._createCorrectError (http://localhost:7357/assets/vendor.js:117533:25)
at Class.handleResponse (http://localhost:7357/assets/vendor.js:117528:25)
at Object.jqXHR.done.fail (http://localhost:7357/assets/vendor.js:117380:41)
at fire (http://localhost:7357/assets/vendor.js:3609:31)
at Object.fireWith [as rejectWith] (http://localhost:7357/assets/vendor.js:3739:7)
at done (http://localhost:7357/assets/vendor.js:9648:14)
at XMLHttpRequest.<anonymous> (http://localhost:7357/assets/vendor.js:9889:9)
You shouldn't need the api key to run the tests. Have you tried the super rentals repo to see if it has the same issue? https://github.com/ember-learn/super-rentals
If it does have the same problem we'll probably need to PR a fix to the tutorial.
Update
I see that the integration test in question is missing a stub maps service definition. It is there in the rentals repo, but not mentioned in the guides tutorial. See https://github.com/ember-learn/super-rentals/blob/master/tests/integration/components/rental-listing-test.js for the code. I've added this info to an issue for updating the guides: https://github.com/ember-learn/guides-source/issues/347
So I finally had time to look at it. The problem is that this is set up for the external map service to use an environment variable for an API key. This is why it runs the app fine (I use KEY=value ember s to start the app) but the tests were not. Simply using KEY=value ember t -s causes these tests to pass. And I'm left with only linting issues.
For the record, this is the sort of thing that should be in the tutorial itself, and I'm not sure why I didn't think of it before.

What is the purpose of using a mock ajax call in testing?

I'm learning about TDD React here and don't understand the below test situation:
it('Correctly updates the state after AJAX call in `componentDidMount` was made', (done) => {
nock('https://api.github.com')
.get('/users')
.reply(200, [
{ 'name': 'Reign', 'age': 26 }
]);
// Overwrite, so we can correctly reason about the count number
// Don't want shared state
wrapper = mount(<UsersListComponent />);
setTimeout(function() {
expect(wrapper.state().usersList).to.be.instanceof(Array);
expect(wrapper.state().usersList.length).to.equal(1);
expect(wrapper.state().usersList[0].name).to.equal('Reign');
expect(wrapper.state().usersList[0].age).to.equal(26);
nock.cleanAll();
done();
}, 1500);
});
What is the purpose of using nock to fake a request? This request doesn't do anything and I'm not sure where the response goes to. I thought TDD approach is to write the test (the code starting at wrapper), see it fail, and then use a real ajax call in the actual component to test. I don't see what nock does here.
The purpose of the nock call in your code is to fake an API request. Nock captures / intercepts the call and instead of the actual response it returns a response with fake information.
The title of the test is Correctly updates the state after AJAX call... so the intention is to test whether the state is updated correctly, and not whether the actual API request has been successfully carried out.
This allows you to model and test different scenarios, for example, how your app behaves when receiving different datasets. It also allows you to complete your tests when the actual API may not be ready yet.
The purpose of Unit Testing is to be only testing your code is the most isolated way possible. Faking an AJAX request and getting its responses is a very common practice to avoid issues with your endpoint (since this is not what you are testing anyway) and focusing on the code handling the response of this endpoint, and you can choose different models of response to test different scenarios.
Nock will simply feed the response back to your component when your call to 'https://api.github.com/users' is made

When using Jasmine's exceptGET / $httpBackend, what's the benefit of having .respond()?

I am using the book called AngularJS Up and Running. It gives an example of using exceptGET. This is the example:
mockBackend = $httpBackend;
mockBackend.exceptGET('/api/note')
.respond([{id:1, label: 'Mock'}]);
My question is, isn't the point of unittesting server calls to make the server call and verify that the server call is what we expect it to be?
With the above code, does it not just make a server call and force the response to equal [{id:1, label: 'Mock'}]? What's the point of doing it if we aren't able to check what the actual response is?
Because later on in the code, it checks the response like so:
mockBackend.flush();
expect(ctrl.items).toEqual([{id:1, label: 'Mock'}]);
Wouldn't it Always equal [{id:1, label: 'Mock'}] because that's what we forced the response to equal? What's the benefit of having .respond() and controlling the response?
If you would actually hit an API endpoint on the server in your unit test, it would not be a unit test anymore - it would now involve much more than just your component under test (controller/service/provider etc) - the network, the web server, the backend itself, probably a database etc - now this becomes an integration test or a system/functional test.
Your unit test would not be isolated anymore and would depend on more things than it should. The point of mocking is to make the test isolated, independent and imitate certain desired conditions - in this case an HTTP response - and then check how your component under test would react.
expect(ctrl.items).toEqual([{id:1, label: 'Mock'}]);
This expect call itself, at least, would check that the mock was successfully applied and the items controller variable contains the mocked response.
Please see more at:
Unit tests vs Functional tests
What is Mocking?

Categories

Resources