0

被测代码

// imports

const router = express.Router()

// This is what needs to be mocked
const client = new AwesomeGraphQLClient({
  endpoint: process.env.GRAPHCMS_URL || '',
  fetch,
  fetchOptions: {
    headers: {
      authorization: `Bearer ${process.env.GRAPHCMS_TOKEN}`
    }
  }
})

interface LoginRequest {
  email: string
  password: string
}

router.post(
  '/login',
  async (req: Request<{}, {}, LoginRequest>, res: Response) => {
    try {
      const JWT_SECRET = getEnvironment('JWT_SECRET')
      const { email, password } = req.body

      if (!email || !password) {
        res.status(400).json({
          message: 'auth.provide.credentials',
          full: 'You should provide an email and password'
        })

        return
      }

      if (!JWT_SECRET) {
        res.status(500).json({
          message: 'auth.secret.not.found',
          full: 'Secret not found'
        })

        // TODO error logging
        return
      }

      const { appUsers } = await client.request<
        GetUserByEmailResponse,
        GetUserByEmailVariables
      >(getUserByEmailQuery, {
        email
      })

      if (appUsers.length === 0) {
        res.status(404).json({
          message: 'auth.wrong.credentials',
          full: 'You provided wrong credentials'
        })

        return
      }

      const user = appUsers[0]

      const result: boolean = await bcrypt.compare(password, user.password)

      if (result) {
        var token = jwt.sign({ id: user.id, email: user.email }, JWT_SECRET)

        res.status(200).json({
          token
        })

        return
      }

      res.status(200).json({
        message: 'auth.wrong.credentials',
        full: 'You provided wrong credentials in the end'
      })
    } catch (e) {
      console.log('E', e)
      const error: ErrorObject = handleError(e)
      res.status(error.code).json(error)
    }
  }
)

测试上面的代码

import request from 'supertest'
import app from '../../../app'
import { mocked } from 'ts-jest/utils'
import { compare } from 'bcrypt'
import { AwesomeGraphQLClient } from 'awesome-graphql-client'

const mockRequestFn = jest.fn().mockReturnValue({
  appUsers: [
    {
      id: 'tests'
    }
  ]
})

jest.mock('awesome-graphql-client', () => ({
  AwesomeGraphQLClient: jest.fn().mockImplementation(() => ({
    request: mockRequestFn
  }))
}))

我正在尝试在 Awesome GraphQL 的非默认导出类上模拟一个方法。我也想窥探这个方法,所以我创建了一个单独jest.fn()的带有返回值的方法。问题是 request 不是一个函数:TypeError: client.request is not a function.

如何模拟和监视模拟的非默认导出类的方法?

解决方案

设法找到解决方法。使该方法成为返回调用的 mockRequest 的函数。这样你就可以AwesomeGraphQLClient.requestmockRequest.toHaveBeenCalledTimes(x).

let mockRequest = jest.fn().mockReturnValue({
  appUsers: [
    {
      id: 'tests'
    }
  ]
})

jest.mock('awesome-graphql-client', () => {
  return {
    AwesomeGraphQLClient: jest.fn().mockImplementation(() => {
      return {
        request: () => mockRequest()
      }
    })
  }
})
4

0 回答 0