首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Typedi + Jest + sequelize + Typescript

Typedi + Jest + sequelize + Typescript
EN

Stack Overflow用户
提问于 2021-06-12 01:56:46
回答 1查看 199关注 0票数 0

我正在努力弄清楚如何对我的服务进行单元测试:

这就是我所拥有的:

userChecklistService.ts:

代码语言:javascript
复制
@Service()
export class UserChecklistsService {
            constructor(
        private userChecklistsRepository: UserChecklistsRepository,
        private userChecklistsSolvedRepository: UserChecklistsSolvedRepository,
    ) { }

    async findAll() {
        const response = await this.userChecklistsRepository.findAll({
            attributes: { ... }

userCheckListRepository

代码语言:javascript
复制
import * as S from '@sequelize'
import { Purchase, PurchaseAssociationMethods } from './Purchase.model'
import { UserChecklistsSolved, UserChecklistsSolvedAssociationMethods } from './UserChecklistsSolved.model'
/**
 * UserChecklists table fields
 */
export interface IUserChecklists {
    id: number
    purchaseId: number
    approved: boolean
    obs: string | null
    createdAt: Date
    updatedAt: Date
}

/**
 * UserChecklists creation fields
 */
export type ICreationUserChecklists = S.Optional<IUserChecklists, 'id'|'obs'>
/**
 * Indexes
 */
const PrimaryIndex = S.BTREEIndex({ name: 'PRIMARY', unique: true })
/**
 * UserChecklists table model
 */
@S.Table({
    tableName: 'user_checklists',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    deletedAt: false,
})
export class UserChecklists extends S.Model<IUserChecklists, ICreationUserChecklists> implements IUserChecklists {
    /**
     * Fields
     */
    @S.PrimaryKey
    @S.AutoIncrement
    @S.NotNull
    @PrimaryIndex
    @S.Column({ type: S.DataType.INTEGER, allowNull: false })
    id: number

    @S.NotNull
    @S.ForeignKey(() => Purchase)
    @S.Column({ type: S.DataType.INTEGER, allowNull: false, unique: true })
    purchase_id: number

    @S.Column(S.DataType.STRING(255))
    obs: string | null

    @S.NotNull
    @S.Column({ type: S.DataType.TINYINT, allowNull: false })
    approved: number
    /**
     * Timestamps
     */
    @S.CreatedAt
    @S.Column({ type: S.DataType.DATE, field: 'created_at' })
    createdAt: Date

    @S.UpdatedAt
    @S.Column({ type: S.DataType.DATE, field: 'updated_at' })
    updatedAt: Date
    /**
     * Associations
     */
    @S.BelongsTo(() => Purchase, 'purchase_id')
    purchase: Purchase

    @S.HasOne(() => UserChecklistsSolved, 'user_checklists_id')
    userChecklistsSolved: UserChecklistsSolved
}
/**
 * Association types
 */
export type UserChecklistsAssociationMethods = S.AssociationMethods<'UserChecklists', UserChecklists>
/**
 * UserChecklists associations
 */
type UserChecklistsAssociations =
    & PurchaseAssociationMethods['belongsTo']
    & UserChecklistsSolvedAssociationMethods['hasOne']
/**
 * UserChecklists Repository
 */
@S.Repository(() => UserChecklists) <-------------
export class UserChecklistsRepository extends S.RepositoryClass<UserChecklists, UserChecklistsAssociations> { }

我的userChecklistService.test.ts

代码语言:javascript
复制
import { UserChecklistsService } from "../userChecklists.service";
import { UserChecklistsRepository, UserChecklistsSolvedRepository } from '@models';
import { mocked } from "ts-jest/utils";

jest.mock('../../models/UserChecklists.model.ts', () => {
    const repo = { findAll: jest.fn() }
    return { UserChecklistsRepository: jest.fn(() => repo) }
})

jest.mock('../../models/UserChecklistsSolved.model.ts', () => {
    const repo = { findAll: jest.fn() }
    return { UserChecklistsSolvedRepository: jest.fn(() => repo) }
})

describe('test', () => {

    let service;

    beforeAll(() => {
        const mockedUserChecklistRepo = mocked(new UserChecklistsRepository(), true)
        const mockedUserChecklistSolvedRepo = mocked(new UserChecklistsSolvedRepository())
        service = new UserChecklistsService(mockedUserChecklistRepo, mockedUserChecklistSolvedRepo)
    })

    it('test', () => {

    })
})

问题是,我不知道如何模拟我的repos。执行上述操作时,会出现以下错误:

代码语言:javascript
复制
src/services/__tests__/userChecklist.service.test.ts:22:45 - error TS2345: Argument of type 'MockedObjectDeep<UserChecklistsRepository>' is not assignable to parameter of type 'UserChecklistsRepository'.
      Type 'MockInstance<UserChecklists & { getPurchase: BelongsToGetAssociationMixin<Purchase>; } & { setPurchase: BelongsToSetAssociationMixin<Purchase, number>; } & { ...; } & { ...; } & { ...; } & { ...; }, []> & { ...; } & { ...; }' provides no match for the signature 'new (): UserChecklists & { getPurchase: BelongsToGetAssociationMixin<Purchase>; } & { setPurchase: BelongsToSetAssociationMixin<Purchase, number>; } & { ...; } & { ...; } & { ...; } & { ...; }'.

    22         service = new UserChecklistsService(mockedUserChecklistRepo, mockedUserChecklistSolvedRepo)
EN

回答 1

Stack Overflow用户

发布于 2021-06-22 11:11:14

在这里,我认为它应该是这样的:(不稍微修改一下就不能确定)

代码语言:javascript
复制
jest.mock('../../models/UserChecklists.model.ts', () => {
    ...jest.requireActual('../../models/UserChecklists.model.ts'),
    UserChecklistsRepository: () => ({ 
       findAll: jest.fn() 
    })
})

我最后一次使用它是这样的:

代码语言:javascript
复制
jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useHistory: () => ({
    push: jest.fn()
  })
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67941557

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档