nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
66.9k stars 7.55k forks source link

Spying on request-scoped provider useless #2875

Closed xxluke closed 5 years ago

xxluke commented 5 years ago

Bug Report

Current behavior

When you spy on a request-scoped provider in a unit test, it does not spy on the same instance of the provider which is called in the later code.

Input Code

Example repo: https://github.com/xxluke/nestjs-typescript-starter

@Injectable({scope: Scope.REQUEST})
export class AppService {
    @Inject(REQUEST)
    private readonly request: Request;

    getHello(): string {
        return 'Hello World!';
    }
}
describe('AppController', () => {
    let appController: AppController;
    let appService: AppService;

    beforeAll(async () => {
        const app = await Test.createTestingModule({
            imports: [AppModule],
        }).compile();

        appController = await app.resolve<AppController>(AppController);
        appService = await app.resolve<AppService>(AppService);
    });

    describe('getHello', () => {
        it('should call AppService', () => {
            const spy = jest.spyOn(appService, 'getHello');
            appController.getHello();
            expect(spy).toHaveBeenCalled();
        });
    });
});

Expected behavior

Test succeeds.

Environment


Nest version: 6.6.4
kamilmysliwiec commented 5 years ago

You have created 2 different fake requests here, hence, you have 2 different instances. I'll describe how it works asap, ref https://github.com/nestjs/docs.nestjs.com/issues/623

lock[bot] commented 4 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.