我刚开玩笑,遇到了一些奇怪的事情:
我得到了这个测试:
let mockedLogger = require('../util/testLogger');
jest.mock('../../handler/util/winstonLogHandler', () => {
return {
getLogger: function() {
return mockedLogger;
},
};
});
const sendMock = jest
.fn()
.mockImplementationOnce(() => {
return new Promise(function(resolve, reject) {
resolve('something');
});
})
.mockImplementationOnce(() => {
return new Promise(function(resolve, reject) {
reject('some error');
});
});
const message = {
channel: {
send: sendMock,
},
};
const ping = require('../.././commands/util/ping');
describe('Testing the ping command', () => {
test('it should have properties', () => {
expect(ping.name).not.toBe(undefined);
expect(ping.name).not.toBe(undefined);
expect(ping.name).not.toBe(undefined);
});
describe('it should execute', () => {
test('and send a message', () => {
ping.execute(null, message);
expect(sendMock).toBeCalled();
});
test('or log an error', () => {
ping.execute(null, message);
expect(mockedLogger.error).toBeCalledWith(`Ping: Error sending message: some error`);
});
});
});
testLogger:
const errorLogMock = jest
.fn()
.mockImplementation((log) => console.error(log))
.mockName('errorLog');
module.exports = {
error: errorLogMock,
};
这个模块:
const winstonLogHandler = require('../../handler/util/winstonLogHandler');
const logger = winstonLogHandler.getLogger();
module.exports = {
name: 'ping',
description: 'pong!',
disabled: false,
requireDB: false,
execute(client, message) {
message.channel.send('pong!').catch(error => {
logger.error(`Ping: Error sending message: ${error}`);
});
},
};
现在如果我执行测试,我得到的错误是我的logError Mock函数从未被调用过。虽然在控制台中我看到实现已执行。那么如果从未调用过该函数,可以执行该实现吗?我错过了什么吗?
答案 0 :(得分:0)
将测试更改为:
describe('Testing the ping command', () => {
test('it should have properties', () => {
expect(ping.name).not.toBe(undefined);
expect(ping.name).not.toBe(undefined);
expect(ping.name).not.toBe(undefined);
});
describe('it should execute', () => {
test('and send a message', () => {
await ping.execute(null, message);
expect(sendMock).toBeCalled();
});
test('or log an error', () => {
await ping.execute(null, message);
expect(mockedLogger.error).toBeCalledWith(`Ping: Error sending message: some error`);
});
});
});
解决了这个问题。 Jest没有函数调用,因为异步代码没有完成执行。