I’m trying to increase code coverage in my project by performing simple jasmine tests on basic methods. In my controller, I have this:
function fetchStates() {
$repository.states().all().then(function(data) {
vm.states = data;
});
}
I’m trying to set vm.states, but absolutely nothing I’ve tried will get that THEN to fire. I can mock a repository such that jasmine doesn’t complain that it doesn’t exist, but when i try to run controller.fetchStates(); it simply will not get to that inner line of code. What’s the correct way to mock $repository.states().all().then so that it will allow vm.states = data?
function GetMockFacRepo() {
var facilityPromise = new Promise((resolve, reject) => {
resolve({ id: 1 });
});
return {
states: function () {
return {
id: 0,
all: function () {
then:
{
return facilityPromise
}
}
}
}
};
}
var repo2 = GetMockFacRepo();
spyOn(repo2.states.all, "then").and.callFake(function () { return 1 });
2
Answers
It ended up being a combination of explicitly mocking the repository, creating my own promise instead of using q, and calling the controller constructor with async.
repo code:
Test:
EDIT: The controller calls the method that populates the states property internally, I don't have to call it explicitly to get the property populated
Try the following:
You also maybe have to wait for the promise to resolve before asserting
vm.states = data;
. In Angular 2+, you can usefakeAsync/tick
andfixture.whenStable()
. I am not sure what you can use in Angular 1.