zenstruck / browser

A fluent interface for your Symfony functional tests.
MIT License
185 stars 17 forks source link

Replacing some service in container + validate form #107

Closed nikophil closed 1 year ago

nikophil commented 1 year ago

Hello,

I have troubles mocking some HttpClient instance with the browser after validating a form.

Here is the code:

        $this->browser()
            ->use(function () {
                self::getContainer()->set('test.http_client', new MockHttpClient(new MockResponse()));
            })
            ->visit('/') // some http calls are made here, using the mock client
            ->assertSuccessful()
            ->fillField('form[date]', '2021-11-10') // fill some fields
            ->click('form_search') // this click redirects us on the same page
            ->assertSuccessful() // :boom: 500 => the http_client is not mocked

Adding some dumps give me some clues

            ->use(function () {
                // prints Symfony\Component\HttpClient\MockHttpClient
                dump(self::getContainer()->get('test.http_client')::class);
            })
            ->click('form_search')
            ->use(function () {
                // prints Symfony\Component\HttpClient\RetryableHttpClient
                dump(self::getContainer()->get('test.http_client')::class);
            })

any ideas?

I saw this issue which is somehow related, but I don't even know where I could reuse the same "mocked container" or something else...

thanks for your help!

kbond commented 1 year ago

I think https://github.com/Happyr/service-mocking could help here. Or what about $browser->disableReboot()?

kbond commented 1 year ago

BTW, the built container should be considered immutable - calling set() could have unintended consequences I believe. I think the service mocking library is your best bet. It allows you to swap/mock services and these swapped/mocked services will be used for the remainder of your test - even between kernel reboots/container resets.

nikophil commented 1 year ago

hi @kbond

thanks for your quick answer, $browser->disableReboot() resovled the problem. I know it's not the best solution but it's a quick win.

:pray: