2

I currently have an express app that does a bunch of logic on a controller. One of the steps is to insert a record to the DB ( It uses ObjectionJS models ).

 let user = await this.User.query(trx).insert(userData);

In an attempt to mock out the model, I have done :

let mockUser = {
  query: jest.fn(() => {
    return mockUser;
  }),
  insert: jest.fn(() => {
    return mockUser;
  }),
  toJSON: jest.fn()
};

With this, I wanted to do an assertion:

expect(mockUser.query().insert).toBeCalledWith({ some: 'data' });

It seems I have missed something. When I run the tests, the code would reach the mock function insert. But jest complaints

enter image description here

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Gayan Hewa
  • 2,277
  • 4
  • 22
  • 41

1 Answers1

0

You could use mockFn.mockReturnThis() to return this context.

E.g.

index.js:

export async function main(User) {
  const trx = 'the trx';
  const userData = {};
  let user = await User.query(trx).insert(userData);
  return user.toJSON();
}

index.test.js:

import { main } from './';

describe('47953161', () => {
  it('should pass', async () => {
    let mockUser = {
      query: jest.fn().mockReturnThis(),
      insert: jest.fn().mockReturnThis(),
      toJSON: jest.fn().mockResolvedValueOnce({ id: 1 }),
    };
    const actual = await main(mockUser);
    expect(actual).toEqual({ id: 1 });
    expect(mockUser.query).toBeCalledWith('the trx');
    expect(mockUser.query().insert).toBeCalledWith({});
    expect(mockUser.query().insert().toJSON).toBeCalledTimes(1);
  });
});

unit test result with coverage report:

 PASS  src/stackoverflow/47953161/index.test.ts (10.41s)
  47953161
    ✓ should pass (7ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.783s, estimated 13s

source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/47953161

Lin Du
  • 88,126
  • 95
  • 281
  • 483