当然,我不想在测试中调用任何真实的端点。但是我不知道如何模拟.on()
的{{1}}函数。
我不确定什么是正确的,但是我尝试了https.get()
https.get.on.mockResolvedValue({})
我可以模拟https
.get('https://jsonplaceholder.typicode.com/todos/1', apiRes => {
console.log('statusCode:', apiRes.statusCode);
console.log('headers:', apiRes.headers);
apiRes.on('data', d => {
process.stdout.write(d);
res.status(200).json({
message: 'message'
});
});
})
.on('error', e => {
console.error(e);
res.status(500).json({
error: 'error'
});
});
。但是就算我开玩笑测试,我也会得到https.get()
。如果删除https.get(...).on is not a function
件,我的测试将可以继续。
答案 0 :(得分:0)
这是解决方案:
index.ts
:
import https from 'https';
const response = {
status(code: number) {
console.log('status code: ', code);
return response;
},
json(data: any) {
console.log(JSON.stringify(data));
return response;
}
};
function getTodo(res = response) {
https
.get('https://jsonplaceholder.typicode.com/todos/1', apiRes => {
console.log('statusCode:', apiRes.statusCode);
console.log('headers:', apiRes.headers);
apiRes.on('data', d => {
process.stdout.write(d);
res.status(200).json({ message: 'message' });
});
})
.on('error', e => {
console.error(e);
res.status(500).json({ error: 'error' });
});
}
export { getTodo };
index.spec.ts
:
import { getTodo } from './';
import https from 'https';
import { EventEmitter } from 'events';
describe('test', () => {
const emitter = new EventEmitter();
const httpIncomingMessage = {
on: jest.fn(),
statusCode: 'mock status code',
headers: {
authorization: 'Bearer mocked token'
}
};
https.get = jest.fn().mockImplementation((uri, callback?) => {
if (callback) {
callback(httpIncomingMessage);
}
return emitter;
});
it('should get todo correctly', () => {
getTodo();
});
it.only('should trigger error event handler correctly', done => {
getTodo();
emitter.emit('error', 'error message');
process.nextTick(() => {
done();
});
});
});
单元测试结果:
PASS src/stackoverflow/57283122/index.spec.ts
test
✓ should get todo correctly (10ms)
✓ should trigger error event handler correctly (14ms)
console.log src/stackoverflow/57283122/index.ts:17
statusCode: mock status code
console.log src/stackoverflow/57283122/index.ts:18
headers: { authorization: 'Bearer mocked token' }
console.log src/stackoverflow/57283122/index.ts:17
statusCode: mock status code
console.log src/stackoverflow/57283122/index.ts:18
headers: { authorization: 'Bearer mocked token' }
console.error src/stackoverflow/57283122/index.ts:26
error message
console.log src/stackoverflow/57283122/index.ts:5
status code: 500
console.log src/stackoverflow/57283122/index.ts:9
{"error":"error"}
console.error src/stackoverflow/57283122/index.ts:26
error message
console.log src/stackoverflow/57283122/index.ts:5
status code: 500
console.log src/stackoverflow/57283122/index.ts:9
{"error":"error"}
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 1.104s, estimated 3s