How to test a text handler in telegraf.js

21 Views Asked by At

I am unable to test the text handler in telegraf.js.

I have a listener that is set in the class constructor.

this.on(message.message('text'), async (ctx) => this.processText(ctx));

I am trying to test it using mocha assert + sinon. I want to simulate the text listener and call the processText function in the test, but the listener refuses to listen to anything. If anyone knows what I'm doing wrong, please let me know. There is also a method bot.handleUpdate() where you can pass the message to the handler, but for some reason, this method is unavailable in my scene.

runAuthSceneTests() {
    let auth;
      
    beforeEach(() => {
      auth = new AuthScene(this.queries, this.cfg);
    });
      
    describe('Обработчик ON message для класса AuthScene', () => {
      afterEach(() => {
        sinon.restore();
      });

      it('В данном тесте должен вызваться метод processText, после того как пользователь отправит сообщение боту', async () => {  
        const ctx = { message: { text: 'test' } };
        const processTextStub = sinon.stub(auth, 'processText').resolves();
        auth.on(message.message('text'), ctx);
        assert(processTextStub.calledOnce);
      });
    });
    
    after(() => {
      setTimeout(() => {
        process.exit(0);
      }, 1500);
    });
  }
1

There are 1 best solutions below

0
agentx On

Solution of the method call handler found and passed to the context of its instance

it('1) В данном тесте должен вызваться метод processText, после того как пользователь отправит сообщение боту', async () => {
        const processTextStub = sinon.stub(auth, 'processText');
        const ctx = new Context({ message: { text: 'test message' } });
        await auth.handler(ctx);
        assert(processTextStub.calledOnce);
      });