问题
I'm having some issues using Jasmine to write tests which spy on a Javascript getter. It causes my test suite to hang (using karma + phantomJS) and then ultimately the browser disconnects having never progressed further than the test in question.
A simple example is probably the easiest way to explain (using ES6 transpiled with webpack + babel-loader):
class ExampleClass {
get name() {
return "My Name";
}
}
In order to change what this get method returns for my test, I am trying the following:
describe("example class getter"), function() {
it("should return blue", function() {
let exampleClass = new ExampleClass();
spyOn(exampleClass, 'name').and.returnValue('blue');
expect(exampleClass.name).toBe('blue');
});
});
This results in the following (where the test in question is my 7th test):
PhantomJS 1.9.8 (Mac OS X 0.0.0): Executed 6 of 8 SUCCESS (0 secs / 0.02 secs)
WARN [PhantomJS 1.9.8 (Mac OS X 0.0.0)]: Disconnected (1 times), because no message in 10000 ms.
PhantomJS 1.9.8 (Mac OS X 0.0.0): Executed 6 of 8 DISCONNECTED (10.003 secs / 0.02 secs)
DEBUG [karma]: Run complete, exiting.
spyOn is working for other methods which aren't defined using the get syntax, so I am confident the build pipeline for transpilation is working fine.
Has anyone seen this before, or have any ideas about a fix?
回答1:
I've got the same. Here's the way I've solved this:
class Foo {
get status() {
return 0;
}
}
So mock this Foo for test:
class FooMock extends Foo {
_fakeStatus() {
return 1;
}
get status() {
return this._fakeStatus();
}
}
And then you use the FooMock
instead the Foo
! e.g:
it('check the status', () => {
spyOn(fooInstance, '_fakeStatus').and.returnValue(3);
expect(fooInstance.status).toBe(3);
}
Hope this works for you! :)
回答2:
I think you neglected to invoke the name
function in your expect call. Like this:
describe("example class getter"), function() {
it("should return blue", function() {
let exampleClass = new ExampleClass();
spyOn(exampleClass, 'name').and.returnValue('blue');
expect(exampleClass.name()).toBe('blue');
});
});
来源:https://stackoverflow.com/questions/31338197/jasmine-spyon-javascript-getter-causing-karma-to-hang