5

How to mix Jest expect with Detox expect? Here is what I try to do. It seem expect has overrided the jest expect.

await mockServer.mockAnyResponse({
    httpRequest: {
      method: 'POST', 
      path: '/api/register',
    },
    httpResponse: {
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        token: 'xxx',
      }),
    }
});

await element(by.id('name')).typeText('Robert');
await element(by.id('password')).typeText('123456');
await element(by.id('register')).tap();

// Check if endpoint has been called
let result = await mockServer.checkIfRegisterEndPointHasBeenCalled();
expect(result).toBe(true); // <-- how to do something like this?
skyboyer
  • 22,209
  • 7
  • 57
  • 64
invisal
  • 11,075
  • 4
  • 33
  • 54

5 Answers5

5

This is done in two steps:

  1. When you use detox.init(), pass a false initGlobals parameter, e.g.: detox.init({ initGlobals: false }). This will disable overriding global vars like expect of Jest.
  2. Use detox public variables through const { device, expect } = require('detox'); or a similar ES6 import.
noomorph
  • 837
  • 1
  • 6
  • 14
  • 2
    ES6 import is still not supported in node, you'll have to Babel your tests for that, which greatly complicates setup. – Rotemmiz Jul 26 '18 at 22:34
  • The documentation shows `detox.init(config, {initGlobals: false});`. Does that have the same outcome as `detox.init({ initGlobals: false })`, or is one of them wrong? – tom Oct 29 '18 at 14:28
2

Another alternative is to ignore the fact that Detox overwrote expect, and re-import Jest's expect under a different name.

const jestExpect = require('expect');

tom
  • 2,335
  • 1
  • 16
  • 30
1

Not sure if this is obvious to a more experienced "tester", but the two other answers are only partially correct, and are missing something that I had a bit of trouble with: you get undefined when you try to access or require expect globally, you have to do that within the test.

So you'll have to do the following:
In the init.js file:

before(async () => {
  await detox.init(config, {initGlobals: false});
});

In your test file - either the actual it (with const) or the before (with let jestExpect in the describe):

jestExpect = require('expect');
MikeL
  • 2,756
  • 2
  • 23
  • 41
0

Now it's can be done in .detoxrc.js by adding behavior object as described in detox docs

https://wix.github.io/Detox/docs/19.x/config/overview#behavior-configuration

If you do not wish to leak Detox globals (expect, device, by, etc.) to the global scope, you can set "exposeGlobals": false and destructure them respectively from the exported Detox interface:

import {by, device, expect as detoxExpect, element} from 'detox';

Jest's expect will work as usual

0

With Jest v29.5, you will need to use const { expect: jestExpect } = require('expect'); instead of const jestExpect = require('expect');

gusgard
  • 905
  • 1
  • 10
  • 24