使用 sinon 在节点 Tap 中模拟 fastify auth 插件

问题描述 投票:0回答:1

我正在尝试使用 Sinon 模拟 fastify-auth 插件的返回值,但似乎我错过了一些东西。 这是我的实现:

// routes.js

const fastifyAuth = require('fastify-auth')
const gipAuth = require('./share/fastify/gip-bearer-auth-plugin')

async function restv2 (fastify) {
  fastify
    .register(gipAuth)
    .post('/test', require('./controllers/test').test)
}

module.exports = async function (fastify) {
  await fastify.register(fastifyAuth)
  return fastify
    .register(restv2, { prefix: '/v2' })
}
// gip-bearer-auth-plugin.js

const fp = require('fastify-plugin')

const { verifyGipToken } = require('../helpers/verifyGipToken')

const verifyGipTokenPlugin = async fastify =>
  fastify
    .addHook('onRequest', fastify.auth([verifyGipToken]))

module.exports = fp(verifyGipTokenPlugin)
// verifyGipToken.js
const AuthorizationError = require('../errors/authorization-error')

async function verifyGipToken (req) {
  throw new AuthorizationError('verifyGipToken is not implemented)
}

module.exports = { verifyGipToken }

这是我尝试在测试文件中模拟模块的部分

// test.js
const t = require('tap')
const sinon = require('sinon')
const verifyGipToken = require('/path/to/verifyGipToken')


t.test('test case', async t => {
  const sandbox = sinon.createSandbox()

  t.beforeEach(async t => {
    sandbox.stub(verifyGipToken, 'verifyGipToken').callsFake(async req => {
      console.log('verifyGipToken stubb called')
      return true
    })
  })

  t.afterEach(async t => {
    sandbox.restore()
  })

我正在记录的部分没有显示在控制台中,我只得到原始代码的结果

javascript node.js sinon fastify tap
1个回答
-1
投票

以下是纠正测试设置的方法:

const t = require('tap');
const sinon = require('sinon');
const verifyGipToken = require('/path/to/verifyGipToken'); // Verify the path

t.test('test case', async t => {
  const sandbox = sinon.createSandbox();

  t.beforeEach(async t => {
    sandbox.stub(verifyGipToken, 'verifyGipToken').resolves(true); // Use `resolves` for asynchronous stubs
  });

  t.afterEach(async t => {
    sandbox.restore();
  });

  t.test('your test description', async t => {
    // Your test code here
    // If you're making HTTP requests, ensure that Fastify is using the stubbed function.
    // For example, in your test, you can await the route handler and check if the stub was called.
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.