[英]Unit test say that cannot read property 'map' of undefined
I'm trying to run a unity test on a method by mocking an addressList but it says that it cannot read the property of undefined.我正在尝试通过 mocking 和 addressList 对方法运行统一测试,但它说它无法读取未定义的属性。
The method:方法:
async paginate(
user: User,
options: IPaginationOptions,
): Promise<Pagination<AddressResponse>> {
const pagination = await this.addressRepository.paginate(user, options);
return new Pagination(
await Promise.all(
pagination.items.map(async (address) => new AddressResponse(address)),
),
pagination.meta,
pagination.links,
);
}
The problem is, when I put a console.log() to read the variable "pagination" it shows me an array that is not empty on the concole:问题是,当我放置一个 console.log() 来读取变量“pagination”时,它向我显示了一个在 concole 上不为空的数组:
console.log
addressList: [ Address {} ]
this is what the repository is returning to me.这就是存储库返回给我的内容。
The test that I'm trying to run is this one:我要运行的测试是这个:
describe('AddressService', () => {
let addressService: AddressService;
const user = new User();
const addressList: Address[] = [new Address()];
console.log('addressList: ', addressList);
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AddressService,
{
provide: getRepositoryToken(AddressRepository),
useValue: {
paginate: jest.fn().mockResolvedValue(addressList),
create: jest.fn(),
save: jest.fn(),
findById: jest.fn(),
findOne: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
},
],
}).compile();
addressService = module.get<AddressService>(AddressService);
});
it('should be defined', () => {
expect(addressService).toBeDefined();
});
describe('paginate', () => {
it('should return an address list successfully', async () => {
// Act
const result = await addressService.paginate(user, {
page: 1,
limit: 10,
});
// Assert
expect(result).toEqual(addressList);
});
});
});
What is the issue with my code?我的代码有什么问题? I'm trying to fix this by days.
我正试图在几天内解决这个问题。
Your paginate
variable is indeed defined and populated, but the property you first accecss in the code is not.您的
paginate
变量确实已定义和填充,但您在代码中首先访问的属性不是。 You try to access paginate.items
while your mock just returns an array of Address
.您尝试访问
paginate.items
而您的模拟仅返回一个Address
数组。 Change your paginate
mock to be paginate: jest.fn().mockResolvedValue({ items: addressList })
and it should be fixed将您的
paginate
模拟更改为paginate: jest.fn().mockResolvedValue({ items: addressList })
它应该被修复
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.