1

I am trying to do unit tests at react components with mocha, chai and sinon.

My first test worked, it is simple checking if component exists and if props are used correctly.

Now I having trouble with ajax on tests.

Here is my code:

import * as React from 'react';
import chai from 'chai';
import TestUtils from 'react-addons-test-utils';
import TransmissorAdd from '../../../middle/transmissors/TransmissorAdd';
import sinon from 'sinon'

const expect = chai.expect

describe('components/transmissors/TransmissorAdd', () => {

    let params = {
        method: 'add'
    }
    var server = null;

    beforeEach(function () {
        server = sinon.fakeServer.create();
    });

    afterEach(function () {
        server.restore();
    });

    it('ajax working', () => {
        // Set up the fake response
        server.respondWith('GET', '/api/client/1/',
            [200, {'Content-Type': 'application/json'},
                JSON.stringify(
                    {
                        "id": 1,
                        "first_name": "firstname",
                        "last_name": "lasname",
                        "account": "0016",
                        "cpf": "55555555555",
                        "rg": "5555555555",
                        "birthdate": "0000-00-00",
                        "street": "Av. street",
                        "number": 881,
                        "complement": "",
                        "district": "xxxxxx",
                        "city": "city",
                        "country": "Brasil",
                        "state": "RS",
                        "zip_code": "00000000",
                        "health_plan": "",
                        "account_phone": "5599999999",
                        "contact_phone": "",
                        "key_box": "",
                        "general_info": ""
                    }
                )
            ]
        );

        server.respondWith('POST', '/api/transmissors/',
            [200, JSON.stringify({'response': 'ok'})]);


        const transmissorAdd = TestUtils.renderIntoDocument(
            <TransmissorAdd params={params} />
        )

        server.respond();
    })

});

I receive this message of error:

 TypeError: Fake server response body should be string, but was undefined
      at responseArray (node_modules/sinon/lib/sinon/util/fake_server.js:31:19)
      at Object.respondWith (node_modules/sinon/lib/sinon/util/fake_server.js:178:67)
      at Context.<anonymous> (assets/js/components/__tests__/middle/transmissors/TransmissorAdd.test.js:55:16)

What's wrong?

Thanks in advance

Alessander França
  • 2,697
  • 2
  • 29
  • 52

1 Answers1

1

It looks like you need to pass empty options {}

server.respondWith('POST', '/api/transmissors/', [200, {}, JSON.stringify({'response': 'ok'})]);

You may use this shorter form

server.respondWith('POST', '/api/transmissors/', JSON.stringify({'response': 'ok'}));
devside
  • 2,171
  • 1
  • 19
  • 23