我创建了一个__mocks__/post.service.ts
来模拟post.service
。
export const findAllFn = jest.fn();
export const PostService = jest.fn().mockImplementation(() => {
return {
findAll: findAllFn,
};
});
并在我的测试中导入项目。
import { PostController } from './post.controller';
jest.mock('./post.service');
import { PostService, findAllFn } from './post.service';
import { TestingModule, Test } from '@nestjs/testing';
describe('Post Controller(jest mock manually loading from mocks files)', () => {
let controller: PostController;
let postService: PostService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [PostService],
controllers: [PostController],
}).compile();
controller = module.get<PostController>(PostController);
postService = module.get<PostService>(PostService);
});
it('should get all posts', async () => {
await controller.getAllPosts();
expect(findAllFn).toHaveBeenCalled();
});
});
运行测试并得到错误。
Module '"./post.service"' has no exported member 'findAllFn'
import { PostService, findAllFn } from './post.service';
但是根据jest docs,应该将其导入。