Ember/Emberfire + Firebase 3 Acceptance Test - ember.js

Prior to firebase 3 update our acceptance test have been running without any issues. We use the following in our beforeTest and afterTest
moduleForAcceptance('Acceptance | Dashboard | Items | Library | New', {
beforeEach() {
stubFirebase();
var ref = createOfflineRef(basicDataRef, 'https://MY-APP.firebaseio.com');
replaceAppRef(this.application, ref);
stubValidSession(this.application, {uid: 'xxxx'});
},
afterEach() {
unstubFirebase();
}
});
basicDataRef is a fixture for the test. The above code allows my to mock session following the test-helper in torii library to allow my application to correctly obtain the data needed as my firebase hieararchy is as follows:
/
+--uid
+--profile
+--otherdata
I am not testing for permission rules, just interaction to save/edit data in the application, and this has worked OK prior to firebase 3 migration. After version 3 all my test returns the following:
actual: >
false
expected: >
true
stack: >
at http://localhost:7357/assets/test-support.js:4130:12
at exports.default._emberTestingAdaptersAdapter.default.extend.exception (http://localhost:7357/assets/vendor.js:49473:7)
at onerrorDefault (http://localhost:7357/assets/vendor.js:41461:24)
at Object.exports.default.trigger (http://localhost:7357/assets/vendor.js:62212:11)
at http://localhost:7357/assets/vendor.js:63463:40
at Queue.invoke (http://localhost:7357/assets/vendor.js:10415:16)
message: >
Error: permission_denied at /xxxx/profile: Client doesn't have permission to access the desired data.
I always thought the createOfflineRef in emberfire allows us to bypass rules checking. the fact that it keeps returning permission_denied is quite perplexing. Maybe i need to re-engineer the test? Or I approach this wrongly all this time? Any input is greatly appreciated

Got to the bottom of this, and I guess I'll answer my own questions in case somebody else experience the same issue as I have.
the new firebase InitializeApp method has an additional optional parameter called name. By default, Emberfire service sets this name to be:
export const DEFAULT_NAME = '[EmberFire default app]';
However the Emberfire test helper to create firebase offline ref stubs the firebase instance with a different instance name to be:
export const DEFAULT_NAME = '[EmberFire offline test app]';
This cause my test to fail with permission denied, as the acceptance test is attempting to connect to the '[EmberFire default app]' and the stubbed offline reference is called something else.
Creating my own create-offline-ref helper substituting the DEFAULT_NAME to '[EmberFire default app]' solves the problem. I'm not sure as to what is the best practice for acceptance test as the change seems deliberate on emberfire.

Related

Cannot mock BlobBaseClient.CanGenerateSasUri of Azure.Blob.Storage

I am currently writing test cases for my blob service.
I have passed almost all of the impediments of Azure.Blob.Storage except one.
I am trying to test a method which generates Url of the blobs which is dependent on CanGenerateSasUri property of the BlobClient. if(blobClient.CanGenerateSasUri){}.
The setup in the test is as below:
var url = new Uri("http://bogus:10000/devstoreaccount1/MyContainer/Blob.mp3");
var blobClient = new Mock<BlobClient>(MockBehavior.Default, url, (BlobClientOptions)null);
blobClient.SetupGet(x => x.CanGenerateSasUri).Returns(true);
But the Moq is complaining:
System.NotSupportedException : Unsupported expression: x => x.CanGenerateSasUri
Non-overridable members (here: BlobBaseClient.get_CanGenerateSasUri) may not be used in setup / verification expressions.
The error is valid as I can see that the property BlobBaseClient.CanGenerateSasUri is not virtual.
I found this(Cannot mock the BlobBaseClient.CanGenerateSasUri property for testing) issue on GitHub.
It is mentioned in the issue that it is already solved and merged in the master branch.
But even in the latest version (12.8.4) the change is not present.
Can someone help me bypass this issue?
Make sure you update to version 12.10.0. I have updated to the latest version 12.10.0 and it is working.

ReferenceError: ga is not defined [Ionic 2.2 Unit Testing With Karma]

I'm adding unit tests to an Ionic 2.2.0 app I manage, but my Components crash at test-time when they encounter Google Analytics code. I'm using Ionic's official unit testing example as a basis, and my current progress can be seen on our public repo.
My project uses Google Analytics, which is added to the HTML and downloaded at runtime (because we have different keys for development vs production).
The code that initializes Analytics is in my main.ts, and it sets a global variable ga, which is subsequently available throughout the application.
I'm beginning the tests for the app's first page, which uses Analytics. When I run the tests, I'm met with the following error
Component should be created FAILED
ReferenceError: ga is not defined
at new MyBusesComponent (webpack:///src/pages/my-buses/my-buses.component.ts:33:6 <- karma-test-shim.js:138419:9)
at new Wrapper_MyBusesComponent (/DynamicTestModule/MyBusesComponent/wrapper.ngfactory.js:7:18)
at CompiledTemplate.proxyViewClass.View_MyBusesComponent_Host0.createInternal (/DynamicTestModule/MyBusesComponent/host.ngfactory.js:15:32)
........
This is because main.ts doesn't seem to be loaded or executed, and I assume TestBed is doing that purposefully. It's certainly better that I don't have the actual Google Analytics object, but the Component does need a function called ga.
My question, therefore, is as follows: how can I create Google Analytics' ga variable in my test configuration such that it's passed through to my components at test-time?
I've tried exporting a function from my mocks file and adding it to either the imports or providers arrays in my spec file, but to no avail.
I appreciate any advice! Feel free to check my code at our repo I linked to above and ask any followups you need. Thanks!
You declare the var ga but that is just to make TypeScript happy. At runtime, the ga is made global from some external script. But this script is not included in the test.
What you could do is just add the (mock) function to the window for the tests. You could probably do this in your karma-test-shim.js.
window.ga = function() {}
Or if you wanted to test that the component is calling the function with the correct arguments, you could just add the function separately in each test that uses the function. For example
beforeEach(() => {
(<any>window).ga = jasmine.createSpy('ga');
});
afterEach(() => {
(<any>window).ga = undefined;
})
Then in your test
it('..', () => {
const fixture = TestBed.creatComponent(MyBusesComponent);
expect(window.ga.calls.allArgs()).toEqual([
['set', 'page', '/my-buses.html'],
['send', 'pageview']
]);
})
Since you're making multiple calls to ga in the constructor, the Spy.calls will get the argument of all each call and put them in separate arrays.

Unit test a polymer web component that uses firebase

I have been trying to configure offline unit tests for polymer web components that use the latest release of Firebase distributed database. Some of my tests are passing, but others—that look nigh identical to passing ones—are not running properly.
I have set up a project on github that demonstrates my configuration, and I'll provide some more commentary below.
Sample:
https://github.com/doctor-g/wct-firebase-demo
In that project, there are two suites of tests that work fine. The simplest is offline-test, which doesn't use web components at all. It simply shows that it's possible to use the firebase database's offline mode to run some unit tests. The heart of this trick is the in the suiteSetup method shown below—a trick I picked up from nfarina's work on firebase-server.
suiteSetup(function() {
app = firebase.initializeApp({
apiKey: 'fake',
authDomain: 'fake',
databaseURL: 'https://fakeserver.firebaseio.com',
storageBucket: 'fake'
});
db = app.database();
db.goOffline();
});
All the tests in offline-test pass.
The next suite is wct-firebase-demo-app_test.html, which test the eponymous web component. This suite contains a series of unit tests that are set up like offline-test and that pass. Following the idea of dependency injection, the wct-firebase-demo-app component has a database attribute into which is passed the firebase database reference, and this is used to make all the firebase calls. Here's an example from the suite:
test('offline set string from web component attribute', function(done) {
element.database = db;
element.database.ref('foo').set('bar');
element.database.ref('foo').once('value', function(snapshot) {
assert.equal(snapshot.val(), 'bar');
done();
});
});
I have some very simple methods in the component as well, in my attempt to triangulate toward the broken pieces I'll talk about in a moment. Suffice it to say that this test passes:
test('offline push string from web component function', function(done) {
element.database = db;
let resultRef = element.pushIt('foo', 'bar');
element.database.ref('foo').once('value', function(snapshot) {
assert.equal(snapshot.val()[resultRef.key], 'bar');
done();
});
});
and is backed by this implementation in wct-firebase-demo-app:
pushIt: function(at, value) {
return this.database.ref(at).push(value);
},
Once again, these all pass. Now we get to the real quandary. There's a suite of tests for another element, x-element, which has a method pushData:
pushData: function(at, data) {
this.database.ref(at).push(data);
}
The test for this method is the only test in its suite:
test('pushData has an effect', function(done) {
element.database = db;
element.pushData('foo', 'xyz');
db.ref('foo').once('value', function(snapshot) {
expect(snapshot.val()).not.to.be.empty;
done();
});
});
This test does not pass. While this test is running, the console comes up with an error message:
Your API key is invalid, please check you have copied it correctly.
By setting some breakpoints and walking through the execution, it seems to me that this error comes up after the call to once but before the callback is triggered. Note, again, this doesn't happen with the same test structure described above that's in wct-firebase-demo-app.
That's where I'm stuck. Why do offline-test and wct-firebase-demo-app_test suites work fine, but I get this API key error in x-element_test? The only other clue I have is that if I copy in a valid API key into my initializeApp configuration, then I get a test timeout instead.
UPDATE:
Here is a (patched-together) image of my console log when running the tests.:
To illustrate the issue brought up by tony19 below, here's the console log with just pushData has an effect in x-element_test commented out:
The offline-test results are apparently false positives. If you check the Chrome console, offline-test actually throws the same error:
The error doesn't affect the test results most likely because the API key validation occurs asynchronously after the test has already completed. If you could somehow hook into that validation, you'd be able to to catch the error in your tests.
Commenting out all tests except for offline firebase is ok shows the error still occurring, which points to suiteSetup(). Narrowing the problem down further by commenting 2 of the 3 function calls in the setup, we'll see the error is caused by the call to firebase.initializeApp() (and not necessarily related to once() as you had suspected).
One workaround to consider is wrapping the Firebase library in a class/interface, and mocking that for unit tests.

How to access a service in an ember acceptance test

Running ember 1.13.6 and ember-cli
I have an ember component which I am trying to acceptance test. It's state is very closely tied to the state of a service within my app and so I would like to directly access that service and change its properties from within my acceptance test.
I have been trying things along the lines of
this.application.__container__.lookup['service:side-bar'])
and
this.application.__container__.cache['service:side-bar'])
but I cannot seem to get the actual active service singleton which my app is using and which I could call get() and set() on.
if I try to use Ember.inject.service i get an obscure error Uncaught TypeError: Object.defineProperty called on non-object(…) which sort of sounds like a bug
I'm successfully getting at a service in 1.13.x by doing something like this:
let myService;
module("Acceptance | xxxxx", {
beforeEach() {
this.application = startApp()
myService = this.application.__container__.lookup('service:my-service');
}
});
Your problem might be that you're trying to use array notation (lookup['my-service']) rather than method invocation (lookup('my-service')).
Hope this helps!

Creating a record with EmberData when testing with Jasmine

I am working on converting a Backbone application into an Ember application using Ember Data. It works fine in the browser but the Jasmine test cases will not pass. When I try to create a record in the Jasmine test case I get this error:
TypeError: 'undefined' is not a function (evaluating 'type._create({ store: this })') in http://localhost:8888/spec/javascripts/generated/assets/application.js (line 26874)
This is the actual code that the error message points to:
createRecord: function(type, properties, transaction) {
properties = properties || {};
// Create a new instance of the model `type` and put it
// into the specified `transaction`. If no transaction is
// specified, the default transaction will be used.
//
// NOTE: A `transaction` is specified when the
// `transaction.createRecord` API is used.
var record = type._create({
store: this // line 26874
});
The actual code that the test case is executing looks like this:
nutrient = App.Nutrient.createRecord({"name_min":"nut 1","female_31_50_min":7.5,"male_31_50_min":8.0,"created_at":"2011-10-10T01:31:53Z","female_51_70_min":8.5,"updated_at":"2011-10-12T12:28:35Z","male_70_plus_min":10.0,"female_19_30_min":6.5,"child_4_8_min":4.0,"male_19_30_min":7.0,"lactating_14_18_min":5.75,"infant_0_05_min":1.0,"female_70_plus_min":9.5,"pregnant_14_18_min":5.8,"infant_6_12_min":2.0,"id":1,"male_9_13_min":5.0,"child_1_3_min":3.0,"female_9_13_min":4.5,"female_14_18_min":5.5,"male_14_18_min":6.0,"lactating_31_50_min":7.75,"pregnant_31_50_min":7.8,"pregnant_19_30_min":6.8,"male_51_70_min":9.0,"lactating_19_30_min":6.75,"female_31_50_max":8.5,"male_31_50_max":9.0,"female_51_70_max":9.5,"male_70_plus_max":11.0,"female_19_30_max":7.5,"child_4_8_max":5.0,"male_19_30_max":8.0,"lactating_14_18_max":6.75,"infant_0_05_max":2.0,"female_70_plus_max":10.5,"pregnant_14_18_max":6.8,"infant_6_12_max":3.0,"male_9_13_max":6.0,"child_1_3_max":4.0,"female_9_13_max":5.5,"female_14_18_max":6.5,"male_14_18_max":7.0,"lactating_31_50_max":8.75,"pregnant_31_50_max":9.8,"pregnant_19_30_max":7.8,"male_51_70_max":10.0,"lactating_19_30_max":7.75})
person = new App.Person.createRecord({age: 0.25})
expect(nutrient.requiredNutrientForPerson(person)).toEqual({min_amount: 1.0, max_amount: 2.0})
Any ideas would be appreciate.
In general, if you're having problems with a test that you don't experience in the browser, it's because the tests are running outside of the Ember run loop.
Try calling Ember.run.sync() before expect() to force synchronization. Alternatively, place any code that involves binding in an anonymous fn inside: Ember.run(function() { }).
Check out the ember and ember-data source for other testing examples, since coverage is pretty solid.
With that said, I'm not an ember-data expert, so I'm not sure if this is the problem you're experiencing.
Sorry, My Bad. The problem is with this line:
person = new App.Person.createRecord({age: 0.25})
I needed to remove the new keyword and it worked correctly