问题
I'm trying to test the asynchronous $resource service by Angular. Firstly note that I don't want to mock $resource, I actually want to get the results and test them.
So basically my getCountries method just uses Angular's $resource to return an array of countries.
Method
getCountries(): any {
var countries = this.$resource(
this.apiEndpoint.baseUrl,
{
'get': {
method: 'GET', isArray: false
}
});
return countries;
}
In my spec I'm having trouble with where to run Jasmine's done() method. Please read comments in the code.
Spec
describe(module', (): void => {
var one;
var SelfRegistrationResourceBuilder;
beforeEach((): void => {
angular.mock.module(
'BuilderModule',
'ngResource'
);
inject(
['Builder', (_SelfRegistrationResourceBuilder _: ISelfRegistrationResourceBuilder ): void => {
SelfRegistrationResourceBuilder = _SelfRegistrationResourceBuilder_;
}]);
});
describe('getCountries', (): void => {
beforeEach((done) => { //done is a parameter in beforeEach
SelfRegistrationResourceBuilder.getCountries().get(
(value: any) => {
console.log("no error");
one = "aValue";
done(); //Do I have to call done() here
}, (error: any) => {
console.log("error");
one = "aValue";
//done(); What about here
})
//done(); ..or here
});
it("should...", (done) => {
expect(one).toBe("aValue");
//done(); and here?
});
});
});
So my problem seems to be that when I run my code I either get the error stated in the title of this problem or if I play around with which done() methods I call then my variable named "one" is undefined, thus implying that the success and error call backs never got called. I can also prove that the success and error callbacks never get called because their console.log()s don't ever print to the console.
Lastly, when I check the network section of the developer tools in my browser I don't see any requests to the server. Could someone please try to help me out here, I think I have most of it figured out except the calling of done().
Thanks
回答1:
done
is for async tests. If you test is not async don't use done
e.g.:
// No done needed
it("should...", () => {
expect(one).toBe("aValue");
});
For async tests call it after the async operation is complete. So :
beforeEach((done) => { //done is a parameter in beforeEach
SelfRegistrationResourceBuilder.getCountries().get(
(value: any) => {
console.log("no error");
one = "aValue";
done(); // Yes call done
}, (error: any) => {
console.log("error");
one = "aValue";
// do not call done. You most likely want to throw to show this is an error case.
})
});
来源:https://stackoverflow.com/questions/36319907/testing-resource-without-mock