japa / runner

Standalone test runner built on top of japa core
MIT License
465 stars 3 forks source link

Error: Cannot import japa test file directly. It must be imported by calling the "japa.run" method #51

Open AlirezaEthDev opened 1 week ago

AlirezaEthDev commented 1 week ago

I use test method in a module (called trade.js) that is included in the main test code (that is functional.spec.js and is in tests\functional folder of Japa project's directory). That's this:

import {test} from '@japa/runner';
import testRequests from './testRequests.js';

export async function trade(){
    test.group('Trade endpoint', (group) => {
        let response
        group.setup(async () => {
        response = await testRequests.trade()
        })
        test('Status code == 200', ({assert}) => {
            assert.equal(response.responseStatusCode, 200)
        });
        test('Status message == OK', ({assert}) => {
            assert.equal(response.responseStatusMessage, 'OK')
        });
        test('Connection == keep-alive', ({assert}) => {
            assert.equal(response.responseHeaders.connection, 'keep-alive')
        });
        test('Properties: {path, price, minMaxReceived}', ({assert}) => {
            assert.properties(response.responseDataObject, ['path', 'price', 'minMaxReceived']);
        });
        test('lenghtOf(path) == 3', ({assert}) => {
            assert.lengthOf(response.responseDataObject.path,3);
        });
        test('lenghtOf(path[0]) == 42', ({assert}) => {
            assert.lengthOf(response.responseDataObject.path[0],42);
        });
        test('lenghtOf(path[1]) == 42', ({assert}) => {
            assert.lengthOf(response.responseDataObject.path[1],42);
        });
        test('lenghtOf(path[2]) == 42', ({assert}) => {
            assert.lengthOf(response.responseDataObject.path[2],42);
        });
        test('typeOf(price) == number', ({assert}) => {
            assert.isNumber(parseFloat(response.responseDataObject.price));
        });
        test('typeOf(minMaxReceived) == number', ({assert}) => {
            assert.isNumber(parseFloat(response.responseDataObject.minMaxReceived));
        });
    })
}

export default{
    trade
}

In there ./testRequests.js is a http client. The below is functional.spec.js that includes trade.js:

import trade from '../../src/utils/trade.js'

tradeTest();

async function tradeTest(){
    for(let i = 0; i < 1000; i++){
        await trade.trade();
    }
}

And this is bin\test.js file:

import { assert } from '@japa/assert'
import { apiClient } from '@japa/api-client'
import { expectTypeOf } from '@japa/expect-type'
import { configure, processCLIArgs, run } from '@japa/runner'
import { createServer } from 'http'

function startHttpServer() {
  const server = createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Server is running');
  });

  server.listen(3000);
  console.log('Test server started on port 3000');

  return server;
}

processCLIArgs(process.argv.splice(2))

configure({
  suites: [
    {
      name: 'unit',
      files: 'tests/unit/**/*.spec.js'
    },
    {
      name: 'functional',
      files: 'tests/functional/**/*.spec.js',
      configure(suite) {
        /**
         * Example showcasing how to start the HTTP
         * server before running tests from the
         * functional suite.
         */
        suite.setup(() => {
          const server = startHttpServer()
          return () => server.close()
        })
      }
    }
  ],
  plugins: [
    assert(),
    expectTypeOf(),
  ],
})

run()

But when I try it with node bin\test.js functional , after six iterations of trad.trade() of functional.spec,js, this error thrown:

   Error: Cannot import japa test file directly. It must be imported by calling the "japa.run" method

   at Object.trade src\utils\trade.js:5
   3|
   4|  export async function trade(){
 ❯ 5|      test.group('Trade endpoint', (group) => {
   6|          let response
   7|          group.setup(async () => {

   ⁃ tradeTest
     tests\functional\functional.spec.js:37
 It seems Japa cannot be executed for a high iteration, am I right?
Dyoma3 commented 3 days ago

@AlirezaEthDev I'm having the same issue for an Adonisjs functional test:

import { test } from '@japa/runner'
// import { UserFactory } from '#database/factories/user_factory'
import { Sports, TournamentFormats } from '#types/tournament'
import ace from '@adonisjs/core/services/ace'
import User from '#models/user'

test.group('Tournament store', async (group) => {
  group.setup(async () => {
    await ace.exec('db:mytruncate', [])
  })

  const userData = {
    username: 'username23',
    firstName: 'First',
    lastName: 'Last',
    email: 'some@example.com',
    password: 'mypassword',
  }

  // const user = await UserFactory.create()
  const user = await User.create(userData)
  const storeData = {
    name: 'Liga ABC',
    sport: Sports.Basketball,
    format: TournamentFormats.RegularSeason,
    areInscriptionsOpen: true,
  }

  test('example test', async ({ assert, client }) => {
    const r = await client.post('/tournaments').json(storeData).loginAs(user)
    r.assertStatus(201)

    assert.include(r.body(), storeData)
  })
})

I'm getting:

Error: Cannot import japa test file directly. It must be imported by calling the "japa.run" method

   at <anonymous> tests/functional/tournament/store.spec.ts:29
   27|    }
   28|  
 ❯ 29|    test('example test', async ({ assert, client }) => {
   30|      const r = await client.post('/tournaments').json(storeData).loginAs(user)
   31|      r.assertStatus(201)

   ⁃ Validator.ensureIsInPlanningPhase
     node_modules/@japa/runner/src/validator.ts:33
   ⁃ test
     node_modules/@japa/runner/index.ts:67

I noticed it throws the error whenever I import the User model or UserFactory. This is very odd, since I have another Adonis project where I do the same but don't get this error.