我目前正在为一个软件编写单元测试,遇到了一个问题,让我困惑了两天。我有一些使用依赖注入模式完成的服务,我可以很好地模拟这些服务,直到我得到具有DynamoDB.DocumentClient依赖的服务。
我尝试了以下方法,使用这个虚构的服务作为示例:cats.service.ts
import { DynamoDB } from 'aws-sdk';
import { Repository } from 'typeorm';
import { CatDTO, CatEntity} from 'somewhere';
export class CatsService {
constructor(
private readonly catRepository: Repository<CatEntity>,
private readonly clientDB: DynamoDB.DocumentClient,
){}
async findCat (name: string): Promise<CatDTO> {
try{
const result = await this.clientDB.query(name).promise();
return result
} catch(error){
throw new Error(error)
}
字符串
问题是:我可以模拟存储库,但不能模拟AWS SDK DynamoDB. DocumentClient。我已经尝试了很多东西,比如jest对模块的手动模拟,jest.mock
直接在代码上执行,如here所述,在这里,here和also here。
问题是我尝试了类似于我对typeorm仓库所做的事情,即:
const mockCatRepository = {
findOne: jest.fn(),
} as unknown as Repository<CatEntity>;
// Here I tried mocking the clientDB DocumentClient in all the ways linked above, such as:
jest.mock('aws-sdk', () => {
return {
DynamoDB: {
DocumentClient: jest.fn(),
},
};
});
describe('CatsService typeorm repository dependency example', () => {
let service: CatsService;
let mockClientDB: DynamoDB.DocumentClient;
beforeEach(() => {
mockClientDB = {} as DynamoDB.DocumentClient;
mockClientDB.query = jest.fn().mockReturnValue({ promise: jest.fn() });
service = new CatsService(
mockCatRepository,
mockClientDB,
);
});
it('should return a cat successfully', async () => {
const mockInput='Peanut';
// and nothing I tried above I could manage to do something like:
const mockDynamoReturn = { Items: [{ name: 'Peanut', breed: 'Tabby' }] };
clientDB.query.promise.mockResolvedValueOnce(mockDynamoReturn)
// since either query or promise don't actually get mocked.
// in this specific case, the following error:
型error TS2339: Property 'mockResolvedValue' does not exist on type '() => Promise<PromiseResult<QueryOutput, AWSError>>'
个
感谢您的时间阅读此!
1条答案
按热度按时间8i9zcol21#
由于可以轻松地为
clientDB
和catRepository
创建模拟对象,并将它们传递给CatsService
的构造函数,因此不需要使用jest.mock()
来模拟整个aws-sdk
模块。例如:
个字符