Node.js 如何使用jest在类中测试函数
我无法使用jest使单元测试正常工作 我试图测试一个正在调用或期望从其他函数得到结果的特定函数,但我不确定它为什么不工作。我对单元测试非常陌生,真的不知道如何让它工作。目前这是我尝试过的Node.js 如何使用jest在类中测试函数,node.js,jestjs,Node.js,Jestjs,我无法使用jest使单元测试正常工作 我试图测试一个正在调用或期望从其他函数得到结果的特定函数,但我不确定它为什么不工作。我对单元测试非常陌生,真的不知道如何让它工作。目前这是我尝试过的 export class OrganizationService { constructor() { this.OrganizationRepo = new OrganizationRepository() } async getOrganizations(req)
export class OrganizationService {
constructor() {
this.OrganizationRepo = new OrganizationRepository()
}
async getOrganizations(req) {
if (req.permission !== 'internal' && req.isAuthInternal === false) {
throw new Error('Unauthenticated')
}
const opt = { deleted: true }
return this.OrganizationRepo.listAll(opt)
}
}
这是我的OrganizationRepository,它扩展了MongoDbRepo
import { MongoDbRepo } from './mongodb_repository'
export class OrganizationRepository extends MongoDbRepo {
constructor(collection = 'organizations') {
super(collection)
}
}
const mongoClient = require('../config/mongo_db_connection')
const mongoDb = require('mongodb')
export class MongoDbRepo {
constructor(collectionName) {
this.collection = mongoClient.get().collection(collectionName)
}
listAll(opt) {
return new Promise((resolve, reject) => {
this.collection.find(opt).toArray((err, data) => {
if (err) {
reject(err)
}
resolve(data)
})
})
}
}
这是MongoDbRepo
import { MongoDbRepo } from './mongodb_repository'
export class OrganizationRepository extends MongoDbRepo {
constructor(collection = 'organizations') {
super(collection)
}
}
const mongoClient = require('../config/mongo_db_connection')
const mongoDb = require('mongodb')
export class MongoDbRepo {
constructor(collectionName) {
this.collection = mongoClient.get().collection(collectionName)
}
listAll(opt) {
return new Promise((resolve, reject) => {
this.collection.find(opt).toArray((err, data) => {
if (err) {
reject(err)
}
resolve(data)
})
})
}
}
这是我做的测试
import { OrganizationService } from '../../../src/services/organization_service'
describe('getOrganizations', () => {
it('should return the list of organizations', () => {
// const OrgRepo = new OrganizationRepository()
const orgService = new OrganizationService()
const OrgRepo = jest.fn().mockReturnValue("[{_id: '123', name: 'testname'}, {_id: '456, name: 'testname2'}]")
// orgService.getOrganizations = jest.fn().mockReturnValue('')
const result = orgService.getOrganizations()
expect(result).toBe(OrgRepo)
})
})
我认为您的测试方式存在两个问题: 1. 您正在尝试测试一个异步方法,在您的测试中,您不会在expect语句之前等待该方法完成 良好的测试结构应为:
it('should test your method', (done) => {
const orgService = new OrganizationService();
const OrgRepo = jest.fn().mockReturnValue("[{_id: '123', name: 'testname'}, {_id: '456, name: 'testname2'}]")
orgService.getOrganizations()
.then((result) => {
expect(result).toEqual(OrgRepo); // I recommend using "toEqual" when comparing arrays
done();
});
})
别忘了把done作为测试的参数
您可以在上找到有关测试异步函数的更多信息
2.
为了正确地测试您的方法,您需要将其与外部依赖项隔离开来。在这里,实际的方法OrganizationRepo.listAll被调用。您希望模拟此方法,例如使用spy,以便控制其结果并仅测试getOrganizations方法。看起来是这样的:
it('should test your method', (done) => {
const req = {
// Whatever structure it needs to be sure that the error in your method is not thrown
};
const orgService = new OrganizationService();
const orgRepoMock = spyOn(orgService['OrganizationRepo'], 'listAll')
.and.returnValue(Promise.resolve("[{_id: '123', name: 'testname'}, {_id: '456, name: 'testname2'}]"));
const OrgRepo = jest.fn().mockReturnValue("[{_id: '123', name: 'testname'}, {_id: '456, name: 'testname2'}]");
orgService.getOrganizations(req)
.then((result) => {
expect(result).toEqual(OrgRepo); // I recommend using "toEqual" when comparing arrays
expect(orgRepoMock).toHaveBeenCalled(); // For good measure
done();
});
})
这样,我们可以确保您的方法是孤立的,并且其结果不能被外部方法改变
对于这个特定的方法,我还建议您根据方法的输入测试错误抛出 我发现您的测试方式存在两个问题: 1. 您正在尝试测试一个异步方法,在您的测试中,您不会在expect语句之前等待该方法完成 良好的测试结构应为:
it('should test your method', (done) => {
const orgService = new OrganizationService();
const OrgRepo = jest.fn().mockReturnValue("[{_id: '123', name: 'testname'}, {_id: '456, name: 'testname2'}]")
orgService.getOrganizations()
.then((result) => {
expect(result).toEqual(OrgRepo); // I recommend using "toEqual" when comparing arrays
done();
});
})
别忘了把done作为测试的参数
您可以在上找到有关测试异步函数的更多信息
2.
为了正确地测试您的方法,您需要将其与外部依赖项隔离开来。在这里,实际的方法OrganizationRepo.listAll被调用。您希望模拟此方法,例如使用spy,以便控制其结果并仅测试getOrganizations方法。看起来是这样的:
it('should test your method', (done) => {
const req = {
// Whatever structure it needs to be sure that the error in your method is not thrown
};
const orgService = new OrganizationService();
const orgRepoMock = spyOn(orgService['OrganizationRepo'], 'listAll')
.and.returnValue(Promise.resolve("[{_id: '123', name: 'testname'}, {_id: '456, name: 'testname2'}]"));
const OrgRepo = jest.fn().mockReturnValue("[{_id: '123', name: 'testname'}, {_id: '456, name: 'testname2'}]");
orgService.getOrganizations(req)
.then((result) => {
expect(result).toEqual(OrgRepo); // I recommend using "toEqual" when comparing arrays
expect(orgRepoMock).toHaveBeenCalled(); // For good measure
done();
});
})
这样,我们可以确保您的方法是孤立的,并且其结果不能被外部方法改变
对于这个特定的方法,我还建议您根据方法的输入测试错误抛出 我能够回答这个问题,首先是我用
jest.mock('path/to/repo')
const mockGetOne = jest.fn()
OrganizationRepository.protorype.getOne = mockGetOne
接下来是测试我能够回答这个问题,首先是我使用
jest.mock('path/to/repo')
const mockGetOne = jest.fn()
OrganizationRepository.protorype.getOne = mockGetOne
接下来是测试我得到了类型错误:无法读取未定义构造函数CollectionName{this.collection=mongoClient.get.collectioncollectionName}的属性集合。抱歉,我想我不清楚,因为我没有添加其他代码。我已经更新了这个问题,我认为这是因为您没有模拟从您正在测试的方法调用的外部方法。我更新了我的答案,希望对你有所帮助!我收到TypeError:无法读取未定义构造函数CollectionName{this.collection=mongoClient.get.collectioncollectionName}的属性collection'。抱歉,我想我不清楚,因为我没有添加其他代码。我已经更新了这个问题,我认为这是因为您没有模拟从您正在测试的方法调用的外部方法。我更新了我的答案,希望对你有所帮助!