我在index.js中有如下明确的POST路由设置
import * as Busboy from 'busboy';
public publish = async (req: Request, res: Response) => {
const busboy = new Busboy({ headers: req.headers });
const pl = { title: '' };
busboy.on('field', (fieldname, val) => {
switch (fieldname) {
case 'title':
pl.title = val;
break;
}
});
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
// Process files
});
busboy.on('finish', async () => {
// Process request
res.send({payload: pl});
});
}
在使用indexest的test index.test.js中,我如何模拟此模块,以便可以验证包含请求中发送的表单字段title
的响应?
目前,我使用jest.mock('busboy');
,但由于这个原因,没有任何调用。
jest.mock('busboy');
let service: ServiceController;
describe('Mosaic Research Capture Service', () => {
it('should publish', async () => {
service = new ServiceController();
const req = {
headers: {
'Content-Type': 'multipart/form-data'
},
body: {}
};
const res = {
send: jest.fn()
};
await service.publish(req, res);
});
});
React客户端如下调用此请求
const formData = new FormData();
formData.append('title', 'SomeTitle');
const header = {
credentials: 'include',
'Content-Type': 'multipart/form-data',
};
const response = await axios.post('/publish, formData, header);
答案 0 :(得分:0)
您需要一个“技巧”来模拟event-listener
动作。问题https://github.com/airbnb/enzyme/issues/426
您多次滥用async/await
,如果您使用Promises,只需使用这些关键字。
这是针对您的情况的建议更新:
index.js
:只需删除所有async
关键字
import * as Busboy from 'busboy';
public publish = (req: Request, res: Response) => {
const busboy = new Busboy({ headers: req.headers });
const pl = { title: '' };
busboy.on('field', (fieldname, val) => {
switch (fieldname) {
case 'title':
pl.title = val;
break;
}
});
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
// Process files
});
busboy.on('finish', () => {
// Process request
res.send({payload: pl});
});
}
index.test.js
import { ServiceController } from "./handler";
import * as Busboy from 'busboy';
jest.mock('busboy');
describe('Mosaic Research Capture Service', () => {
let service: ServiceController;
const mockedEvenMap = {};
beforeAll(() => {
Busboy.mockImplementation(() => {
return { // mock `on` event of Busby instance
on: (event, callback) => {
mockedEvenMap[event] = callback;
},
};
});
service = new ServiceController();
});
afterAll(() => {
Busboy.mockRestore();
});
it('should publish', () => {
const expectedTile = "MY_TITLE";
const filenameToTest = 'title';
const req = {
headers: {
'Content-Type': 'multipart/form-data'
},
body: {}
};
const res = {
send: jest.fn()
};
service.publish(req, res); // remove await
// fire simulate event
mockedEvenMap['field'](filenameToTest, expectedTile);
mockedEvenMap['finish']();
// you expect send function will be call with a payload with includes the title
expect(res.send).toBeCalledWith({ payload: {title: expectedTile} });
});
});