简体   繁体   中英

Mock a $http.put result of an angular model - unit test

I have this test:

Test:

describe('Ao iniciar uma entrevista por id', function () {

        it('deve deve utilizar diretorio raiz da aplicacao', inject(function (Questionario) {
            expect(Questionario.urlEntrevistaPorId).toContain(raiz);
        }));

        it('deve atualizar modelo', inject(function (Questionario, $httpBackend) {
            var entrevistaNova = { a: 1, b: 2 };
            $httpBackend.expectPUT(Questionario.urlEntrevistaPorId, { estudoId: idEstudo, entrevistaId: 666 }).respond({
                Entrevista: entrevistaNova,
                PaginaAtual: novaPagina
            });
            Questionario.iniciarEntrevista(666);
            spyOn(Questionario, 'setEntrevista');
            $httpBackend.flush();
            expect(Questionario.setEntrevista).toHaveBeenCalledWith(entrevistaNova, novaPagina);
        }));

    });

Model Angular:

function iniciarEntrevista(id) {
            var _this = this;
            return $http
                .put(this.urlEntrevistaPorId, { estudoId: idEstudo, entrevistaId: id })
                .success(function (result) {
                    if (result.Iniciada) {
                        _this.setEntrevista(result.Entrevista, result.PaginaAtual);
                        return true;
                    }
                    else {
                        return false;
                    }                 
                });
        }

Which calls Questionario.iniciarEntrevista and waits for setEntrevista to be called. But this method is not being called because of the return of the $http.put.

I need result.Iniciada to be true.

How do I mock this?

One way to use it is to use $httpBackend .

You have there some examples also, basically you inject the $httpBackend inside your testing controller, and map it to a request. You have some examples in the link provided, and I think it is straight forward from here.

Here is a tutorial with a plunker link in it also.

I got it!

It was just add the line Iniciada : true on $httpBackend.expectPUT

Thanks everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM