nestjs jest unit test TypeError when using .lean() for mongo queries - unit-testing

findOne: jest.fn().mockResolvedValue(stub())
this is how I mocked findOne. when using this function for testing it will throw a TypeError
original function = findOne({
key: value
}).lean();
testing perfectly working when we drop lean()
findOne({
key: value
})
findOne({
key: value
}).lean();
NOT WORKING WHEN USE LEAN()
findOne({
key: value
})
WORKING WITHOUT LEAN()

Related

Ember.RSVP.hash and acceptance testing

I have a hash that's called from a service:
return new Ember.RSVP.hash({
locations: ajax(
{
url: applicationConfig.apiUrl + '/api/v1/locations/search?term=' + term
}),
listingEvents: ajax({
url: applicationConfig.apiUrl + '/api/v1/listingevents/search?term=' + term
})
});
Now in my tests I am getting:
✘ Error: Assertion Failed: You have turned on testing mode, which disabled the run-loop's autorun.
You will need to wrap any code with asynchronous side-effects in a run
I have wrapped the hash in an Ember.run but that doesn't work.
What is the best way to get the hash to run in acceptance tests?

Ember CLI Controller Test: Uncaught TypeError: Cannot read property 'transitionToRoute' of null

I have a controller I'm testing with Ember CLI, but the controller's promise will not resolve, as the controller's transitionToRoute method is returning null:
Uncaught TypeError: Cannot read property 'transitionToRoute' of null
login.coffee
success: (response) ->
# ...
attemptedTransition = #get("attemptedTransition")
if attemptedTransition
attemptedTransition.retry()
#set "attemptedTransition", null
else
#transitionToRoute "dashboard"
login-test.coffee
`import {test, moduleFor} from "ember-qunit"`
moduleFor "controller:login", "LoginController", {
}
# Replace this with your real tests.
test "it exists", ->
controller = #subject()
ok controller
###
Test whether the authentication token is passed back in JSON response, with `token`
###
test "obtains authentication token", ->
expect 2
workingLogin = {
username: "user#pass.com",
password: "pass"
}
controller = #subject()
Ember.run(->
controller.setProperties({
username: "user#pass.com",
password: "pass"
})
controller.login().then(->
token = controller.get("token")
ok(controller.get("token") isnt null)
equal(controller.get("token").length, 64)
)
)
When the line #transitionToRoute("dashboard") is removed, the test passes; otherwise, the test fails.
How can I fix this error, while still maintaining my controller logic?
Work around: bypass transitionToRoute if target is null. Something like:
if (this.get('target')) {
this.transitionToRoute("dashboard");
}
I ran into the same error and dug into Ember source code a little bit. In my case this error is thrown by ControllerMixin because get(this, 'target') is null at this line. The test module probably has no idea what target should be in a controller unit test like this without further context, so you may need to manually set it or just bypass it.
Since you're not interested in the transition itself, you can just stub out the transitionToRoute method on the controller.
JS:
test('Name', function() {
var controller = this.subject();
controller.transitionToRoute = Ember.K;
...
}
Coffee:
test "it exists", ->
controller = #subject()
controller.transitionToRoute = Ember.K
ok controller
Not sure why transitionToRoute method is undefined when you execute it within an unit test - it is probably related to the fact that the execution context is different.
One possible workaround to this would be if you move your transitionToRoute call to the route instead of it being in the controller. That way your controller will send action to its route and you'll keep routing only in the route.
There is a big discussion around which is better practice - routing from controller or not but this is another story.

Angular JS/Karma Unit Testing with Angular UI-Router

I'm working on an Angular app that uses Angular UI-Router for routing and maintaining state. I am having a hard time getting my unit test to even compile. It seems that no matter what I do, I keep getting the following error:
Error: State '' is not navigable
I have the following states set up in my app, as well as the following redirects:
app.config(function($stateProvider, $urlRouterProvider) {
var paramList = '?beds&lat&lon&zoom';
$urlRouterProvider
.when('', '/')
.when('/', '/search')
.when('/search', '/search/list')
.otherwise('');
$stateProvider
.state('search', {
abstract: true,
url: '/search',
templateUrl: 'views/search.html',
controller: 'SearchCtrl'
})
.state('search.list', {
url: '/list' + paramList,
templateUrl: 'views/search-list.html'
})
.state('search.map', {
url: '/map' + paramList,
templateUrl: 'views/search-map.html'
})
.state('search.listing', {
url: '/listing/:id' + paramList,
templateUrl: 'views/search-listing.html'
})
.state('favorites', {
url: '/favorites',
templateUrl: 'views/favorites.html'
})
});
I've eaten up an entire day trying to get a single test to work, but no matter what approach I take, I always end up at this same error. I have an e2e test running just fine.
ui-router adds an internal state for '' automatically, so that is the error you are getting. I recommend adding a '/' url for a base state and change the 'otherwise' invocation to redirect to '/' instead of ''. The internal '' state is being attempted because of your .otherwise('') call. So perhaps try this:
$urlRouterProvider
.when('/', '/search')
.when('/search', '/search/list')
.otherwise('/');
At first glance I would say it looks like the $stateProvider is telling you you need to put an empty state in there. Add this to the list of states.
state( '', { ... } )

Testing Ember-data w/Jasmine and DS.FixtureAdapter

I'm trying to do a Jasmine test of ember-data (using the current master) using the DS.FixtureAdapter. I've tried dozens of variations on the below code (with and without trying to create an Application namespace). I've also gone into the ember-data source to try and see what's going on, as well as referenced the tests in ember-data itself as an example.
I've also tried variations of Person.find(1), using Ember.run blocks and Jasmine wait()'s.
Whatever I try, store.find(Person, 'test') returns a result but attempting to get one of the attributes results in null (test assertion fails). What is it I'm not seeing? Thanks for any help!
describe "a test", ->
store = null
Person = null
beforeEach ->
store = DS.Store.create
revision: 11
adapter: 'DS.FixtureAdapter'
Person = DS.Model.extend
firstName: DS.attr('string')
lastName: DS.attr('string')
age: DS.attr('number')
it "works or does it", ->
Person.FIXTURES = [{
id: 'test'
firstName: 'Kyle'
lastName: 'Stevens'
age: 30
}]
kyle = store.find(Person, 'test')
expect(Em.get(kyle, 'firstName')).toEqual('Kyle')
Whatever I try, store.find(Person, 'test') returns a result but attempting to get one of the attributes results in null (test assertion fails). What is it I'm not seeing? Thanks for any help!
This is a timing issue. When you call store.find() it runs query asynchronously and returns a model promise. That means the query is still running (or scheduled to run) when control returns to your test, resulting in a failed expectation.
This is what we love about ember, it means your app can treat kyle as if the data were present and trust that values will be updated automagically via bindings when the data becomes available.
Of course all this magic is not so great when it is preventing your test from passing. Here are some alternative approaches:
1) Register a didLoad callback
kyle = store.find(Person, 'test');
kyle.on('didLoad', function() {
console.log('should = kyle: ', Em.get(kyle, 'firstName'));
});
2) Instead of didLoad could use more blackbox testing approach and just verify that the name is set propertly within 100 ms of having called find - of course this can lead to brittle tests
Ember.run.later(this, function() {
console.log('should = kyle: ', Em.get(kyle, 'firstName'));
console.log('should = kim: ', Em.get(App.kim, 'firstName'));
}, 100);
I believe that in a jasmine test you could wrap your setup code in a runs() method and use waitsFor to verify that the value has been set as expected:
waitsFor(function() {
return Em.get(kyle, 'firstName') == 'Kyle';
}, "x to be set to 5", 100);
See this JSBIN for working (non-jasmine) example:
http://jsbin.com/apurac/4/edit
See this post for tips on async testing with jasmine: http://blog.caplin.com/2012/01/17/testing-asynchronous-javascript-with-jasmine/
Also, be sure to set Ember.testing = true for all of your tests. See this SO post for detail: Is it recommended to set Ember.testing = true for unit tests?

Mobile Application Using Sencha Touch - JSON Request Generates Syntax Error

I started playing a bit with Sencha Touch.
So I've built a really simple application based on one of the examples just to see how it goes.
Basically it creates a JSON Request which executes a Last.FM web service to get music events near the user's location.
Here's the JSON code:
var makeJSONPRequest = function() {
Ext.util.JSONP.request({
url: 'http://ws.audioscrobbler.com/2.0/',
params: {
method: 'geo.getEvents',
location: 'São+Paulo+-+SP',
format: 'json',
callback: 'callback',
api_key: 'b25b959554ed76058ac220b7b2e0a026'
},
callback: function(result) {
var events = result.data.events;
if (events) {
var html = tpl.applyTemplate(events);
Ext.getCmp('content').update(html);
}
else {
alert('There was an error retrieving the events.');
}
Ext.getCmp('status').setTitle('Events in Sao Paulo, SP');
}
})
};
But every time I try to run it, I get the following exception:
Uncaught SyntaxError: Unexpected token :
Anyone has a clue?
A couple of things. First of all the "Uncaught SyntaxError: Unexpected token :" means the browser javascript engine is complaining about a colon ":" that has been put in the wrong place.
The problem will most likely be in the returned JSON. Since whatever the server returns will be run though the eval("{JSON HTTP RESULT}") function in javascript, the most likely thing is that your problem is in there somewhere.
I've put your code on a little sencha test harness and found a couple of problems with it.
First: My browser was not too happy with the "squiggly ã" in location: 'São+Paulo+-+SP', so I had to change this to location: 'Sao+Paulo,+Brazil', which worked and returned the correct results from the audioscribbler API.
Second: I notice you added a callback: 'callback', line to your request parameters, which changes the nature of the HTTP result and returns the JSON as follows:
callback({ // a function call "callback(" gets added here
"events":{
"event":[
{
"id":"1713341",
"title":"Skank",
"artists":{
"artist":"Skank",
"headliner":"Skank"
},
// blah blah more stuff
"#attr":{
"location":"Sao Paulo, Brazil",
"page":"1",
"totalpages":"1",
"total":"2"
}
}
}) // the object gets wrapped with extra parenthesis here
Instead of doing that I think you should be using the callbackKey: 'callback' that comes with the example in http://dev.sencha.com/deploy/touch/examples/ajax/index.js.
Something like this for example:
Ext.util.JSONP.request({
url: 'http://ws.audioscrobbler.com/2.0/',
params: {
method: 'geo.getEvents',
location: 'Sao+Paulo,+Brazil',
format: 'json',
api_key: 'b25b959554ed76058ac220b7b2e0a026'
},
callbackKey: 'callback',
callback: function(result) {
// Output result to console (Firebug/Chrome/Safari)
console.log(result);
// Handle error logic
if (result.error) {
alert(result.error)
return;
}
// Continue your code
var events = result.data.events;
// ...
}
});
That worked for me so hopefully it'll work for you too. Cherio.