我正在尝试使用mocha,chai和sinon对反应组件进行单元测试。
我的第一个测试工作,很简单检查组件是否存在以及道具是否正确使用。
现在我在测试中遇到ajax问题。
这是我的代码:
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();
})
});
我收到此错误消息:
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)
出了什么问题?
提前致谢
答案 0 :(得分:1)
看起来您需要传递空选项{}
server.respondWith('POST', '/api/transmissors/', [200, {}, JSON.stringify({'response': 'ok'})]);
您可以使用此缩短形式
server.respondWith('POST', '/api/transmissors/', JSON.stringify({'response': 'ok'}));