title: Testing mongoose models with NestJS
body: <p>I'm using the mongoose module from NestJS so I have my schema and an interface, and in my service I use @InjectModel to inject my model. I do not realize how I can mock the model to inject in my service.</p>
  
  <p>My service looks like this:</p>
  
  <pre class="lang-js prettyprint-override"><code>    @Injectable()
      export class AuthenticationService {
  
          constructor(@InjectModel('User') private readonly userModel: Model&lt;User&gt;) {}
  
          async createUser(dto: CreateUserDto): Promise&lt;User&gt; {
              const model = new this.userModel(dto);
              model.activationToken = this.buildActivationToken();
              return await model.save();
            }
      }
  </code></pre>
  
  <p>and in my service test, I have this:</p>
  
  <pre class="lang-js prettyprint-override"><code>    const mockMongooseTokens = [
        {
          provide: getModelToken('User'),
          useValue: {},
        },
      ];
  
      beforeEach(async () =&gt; {
          const module: TestingModule = await Test.createTestingModule({
            providers: [
              ...mockMongooseTokens,
              AuthenticationService,
            ],
          }).compile();
  
          service = module.get&lt;AuthenticationService&gt;(AuthenticationService);
        });
  </code></pre>
  
  <p>But when I run the test I got this error:</p>
  
  <pre><code>    TypeError: this.userModel is not a constructor
  </code></pre>
  
  <p>I would also like to get my model to perform unit tests over it, as is shown in this <a href="https://codeutopia.net/blog/2016/06/10/mongoose-models-and-unit-tests-the-definitive-guide/" rel="noreferrer">article</a></p>