Search code examples
angulartypescriptunit-testingmocha.jssinon

How to check http calledWith in Sinon with Typescript/Angular


We are migrating to TypeScript and we want to continue using Sinon for our tests.

Before we used JavaScript Service Unit Tests like this:

it('should get buyer application status count', function () {
        let httpStub = sandbox.stub(http, 'get').returns({
            then: function () {
                return [];
            }
        });


        let result = service.get();

        httpStub.calledWith(`${constants.APPLICATION_BASE}ApiService/GetMethod`).should.be.true;
    });

The service.get() method makes http call to ApiService/GetMethod and we we ensuring that it is called with this exact URL.

How do we the same in TypeScript with Sinon?

At the moment we do this:

it('should get list', () => {
    // Arrange
    let apiServiceStub: SinonStubbedInstance<ApiService>;


    // Act
    apiServiceStub= sinon.createStubInstance(ApiService);

    let result = apiServiceStub.get();

    // Assert -- Here is my question, how to do this line, it doesn't work now
    applicationServiceStub.**calledWith**(`${constants.APPLICATION_BASE}ApiService/GetMethod`).should.be.true;
  });

As it is done now, the calledWith method matches only the passed arguments to the menthod and not how the HTTP call is called. I need something that can create similar to first example - http stub.


Solution

  • Happy to share the solution:

    it('should stub http'), () => {
        let httpStub = sandbo.stub(TestBed.inject(HttpClient), 'post').returns('Whatever');
    
        let result = service.PostSomething();
    
        httpStub.calledWith('YourPostURL').should.be.true;
    }